Ask Your Question
2

How to use the output matrix as an input in Sage

asked 2021-11-09 00:08:06 +0200

dasdipayan9038 gravatar image

updated 2021-11-09 00:30:37 +0200

Suppose [1 2 3] [4 5 6] [5 6 7] is a matrix I get as an output in a file. How can I use the matrix as an input to a different code? It seems the matrix output doesn't have the same input structure in Sagemath.

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
3

answered 2021-11-09 01:08:56 +0200

You can try the sage_input function:

sage: m = matrix(QQ, [[1,2,3], [4,5,6], [7,8,9]])
sage: m
[1 2 3]
[4 5 6]
[7 8 9]
sage: sage_input(m)
matrix(QQ, [[1, 2, 3], [4, 5, 6], [7, 8, 9]])

Save the last line to a file instead of just

[1 2 3]
[4 5 6]
[7 8 9]

The sage_input function is documented here

edit flag offensive delete link more
2

answered 2021-11-09 00:32:36 +0200

Max Alekseyev gravatar image

updated 2021-11-09 00:41:25 +0200

For example, you can parse such matrix printout as

s = '[1 2 3] [4 5 6] [5 6 7]'
M = Matrix(QQ, eval('['+s.replace(' ',',')+']') )
print(M)
edit flag offensive delete link more

Comments

Thank you very much. But how should I use it from a file?

dasdipayan9038 gravatar imagedasdipayan9038 ( 2021-11-09 00:35:29 +0200 )edit

load file's content to a string and proceed as above.

Max Alekseyev gravatar imageMax Alekseyev ( 2021-11-09 00:36:42 +0200 )edit

For a large matrix (say of order 1000 and elements in range(2^15)), this space can be tricky. For instance, there are non-uniform spaces. Thus it might be a little difficult just to use replace space with a comma to define the matrix. Is there any way [2 4 6] can be treated as a vector [2,4,6] in sage?

dasdipayan9038 gravatar imagedasdipayan9038 ( 2021-11-09 01:48:26 +0200 )edit

It's easy to make spacing uniform by replacing two spaces with one until all such paired spaces are gone.

Max Alekseyev gravatar imageMax Alekseyev ( 2021-11-09 03:31:48 +0200 )edit

Thanks. I could able to do the uniformity of spacing using notepad.

dasdipayan9038 gravatar imagedasdipayan9038 ( 2021-11-09 10:19:45 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2021-11-09 00:08:06 +0200

Seen: 395 times

Last updated: Nov 09 '21