# How to use the output matrix as an input in Sage

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 close merge delete

Sort by » oldest newest most voted

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

more

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)

more

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

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

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

( 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?

( 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.

( 2021-11-09 03:31:48 +0200 )edit

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

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