Josh
Josh

Reputation: 151

SageMath: Getting the imaginary part of a matrix

Suppose you have a matrix with complex entries, and you would like to extract the imaginary component of each entry and make a new matrix in Sage. For instance, suppose

M = [[1 + 2i, 5 + 3*i], [5, 3*i]]

I would like to get

M_imag = [[2, 3], [0, 3]]

I am aware that z.imag() returns the imaginary part of a complex number z in sage. Also the following code works for vectors: [z.real() for z in v] but I cannot get it to work for matrices.

I know then NumPy library provides the means for this. But I do not want to change the Sage matrix to numpy. Ultimately, if there is a way to change a NumPy matrix back to Sage, that will work too. I prefer a solution that is independent from other libraries, including NumPy.

How can this be achieved in Sage?

Upvotes: 1

Views: 549

Answers (2)

Samuel Lelièvre
Samuel Lelièvre

Reputation: 3453

Beware that this really defines a list of lists, not a matrix:

sage: M = [[1 + 2*i, 5 + 3*i], [5, 3*i]]

so that it displays like a list of lists:

sage: M
[[2*I + 1, 3*I + 5], [5, 3*I]]

and its "parent" is the class of lists:

sage: parent(M)
<class 'list'>

To define a matrix, use matrix of a list of lists (or of a NumPy array):

sage: M = matrix([[i, 3], [5, i]])

It displays as a matrix:

sage: M
[I 3]
[5 I]

and lives in a space of matrices:

sage: parent(M)
Full MatrixSpace of 2 by 2 dense matrices
over Number Field in I with defining polynomial x^2 + 1 with I = 1*I

Change a whole row or a single entry as follows:

sage: M[0, :] = matrix([[2*I + 1, 3*I + 5]])
sage: M[1, 1] = 3*I

and see the result:

sage: M
[2*I + 1 3*I + 5]
[      5     3*I]

Get LaTeX code for the matrix:

sage: latex(M)
sage: latex(M)
\left(\begin{array}{rr}
2 i + 1 & 3 i + 5 \\
5 & 3 i
\end{array}\right)

See the matrix nicely typeset:

sage: view(M)

Compute the trace and determinant:

sage: M.trace()
5*I + 1
sage: M.det()
-12*I - 31

Apply a map to each entry, e.g. real or imag to get the real part or imaginary part:

sage: A = M.apply_map(real)
sage: B = M.apply_map(imag)

and check the result:

sage: A, B, A + i*B, M
(
[1 5]  [2 3]  [2*I + 1 3*I + 5]  [2*I + 1 3*I + 5]
[5 0], [0 3], [      5     3*I], [      5     3*I]
)

Further reading

Upvotes: 1

Lisa
Lisa

Reputation: 66

I think this will solve your problem [[z.imag() for z in v] for v in M]. You iterate over the rows in M and then you iterate over the elements in each row and compute the imaginary part of it.

Upvotes: 2

Related Questions