# matrix and latex I want to create a matrix with my results and then to obtain the output in latex code. However, the first column are natural number, and the second one are not integers, so I can´t create a matrix with different inputs (Am I right?). How can I do?

edit retag close merge delete

Sort by » oldest newest most voted

For entries in different rings, you could use a nested list. The numpy array data structure is similar, with slightly more functionality (like a transpose method). The latex formatting for numpy arrays probably isn't what you want though, so you can use a simple loop to print the data in the format you want. Here's an example:

sage: ints = primes_first_n(5)
sage: floats = [random() for _ in range(5)]
sage: rats = [1/n for n in range(5,10)]
sage: polys = [x^n for n in range(2,7)]

sage: from numpy import array
sage: mat = array([ints, floats, rats, polys]).transpose()
sage: mat
array([[2, 0.996565962529, 1/5, x^2],
[3, 0.803053692297, 1/6, x^3],
[5, 0.870364288574, 1/7, x^4],
[7, 0.369733125378, 1/8, x^5],
[11, 0.0361132712282, 1/9, x^6]], dtype=object)

sage: for row in mat:
....:     print ' & '.join([latex(_) for _ in row]) + ' \\\\'
....:
2 & 0.996565962529 & \frac{1}{5} & x^{2} \\
3 & 0.803053692297 & \frac{1}{6} & x^{3} \\
5 & 0.870364288574 & \frac{1}{7} & x^{4} \\
7 & 0.369733125378 & \frac{1}{8} & x^{5} \\
11 & 0.0361132712282 & \frac{1}{9} & x^{6} \\

more

I'm a little confused here. If you enter a matrix with different types, it should just find the smallest 'ring' that contains all of them. Usually SR does the trick.

sage: M = matrix([[1,.9,1/5,x^2],[2,1.9,2/5,x^3],[3,2.9,3/5,x^4],[4,3.9,4/5,x^5]])
sage: type(M)<type 'sage.matrix.matrix_symbolic_dense.Matrix_symbolic_dense'>
sage: M
[ 1.00000000000000 0.900000000000000 0.200000000000000               x^2]
[                2  1.90000000000000               2/5               x^3]
[                3  2.90000000000000               3/5               x^4]
[                4  3.90000000000000               4/5               x^5]
sage: latex(M)
\left(\begin{array}{rrrr}
1.00000000000000 & 0.900000000000000 & 0.200000000000000 & x^{2} \\
2 & 1.90000000000000 & \frac{2}{5} & x^{3} \\
3 & 2.90000000000000 & \frac{3}{5} & x^{4} \\
4 & 3.90000000000000 & \frac{4}{5} & x^{5}
\end{array}\right)


Am I misunderstanding the question somehow?

You'll note there is a bug revealed here; the first row for some reason coerces the numerical entries to RR (though not x^2), but the others don't. See Trac 12778.

more

that's how I understood the question too -- nice bug-hunting!

I create the matrix as zero matrix and then I give values of the entries. Maybe it is not the best way to do it. Thanks

1

Oh, no, that is probably not a good way to do it, because the ring of the matrix is set in stone. You can change the ring, but that yields a new matrix.