Hello,

I've heard that in some programming languages it is possible to "mask" your matrix. That is, I should be able to do something like

sage: M = Matrix([[1,2,3],[0,4,5],[0,0,6]])
sage: Z = zero_matrix(ZZ, 3)
sage: ( M == Z )
[False False False]
[True  False False]
[True  True  False]


Or perhaps the matrix outputted would have 0's and 1's (that would be more convenient). Is there a way to do this in Sage, perhaps using some object other than a matrix?

Thanks!

edit retag close merge delete

Sort by » oldest newest most voted That's how numpy matrices work, so one possibility is to write:

sage: M = Matrix([[1,2,3],[0,4,5],[0,0,6]])
sage: M.numpy()
array([[1, 2, 3],
[0, 4, 5],
[0, 0, 6]])
sage: M.numpy() == 0
array([[False, False, False],
[ True, False, False],
[ True,  True, False]], dtype=bool)
sage: M.numpy() == zero_matrix(ZZ, 3)
array([[False, False, False],
[ True, False, False],
[ True,  True, False]], dtype=bool)

more

This is a follow-up to DSM's answer. Just for future reference, I found that I can turn the Trues and Falses into 1's and 0's in the following way:

sage: M = Matrix([[1,2,3],[0,4,5],[0,0,6]])
sage: 1 * ( M.numpy() == 0 )
array([[0, 0, 0],
[1, 0, 0],
[1, 1, 0]])

more There might be a better way, but you can use Python's list comprehensions:

sage: M = Matrix([[1,2,3],[0,4,5],[0,0,6]])
sage: Z = zero_matrix(ZZ, 3)
sage: M.list()
[1, 2, 3, 0, 4, 5, 0, 0, 6]
sage: zip(M.list(), Z.list())
[(1, 0), (2, 0), (3, 0), (0, 0), (4, 0), (5, 0), (0, 0), (0, 0), (6, 0)]


So here is a one-liner to get something like what you want:

sage: Matrix(3, 3, [0 if x==y else 1 for (x,y) in zip(M.list(), Z.list())])
[1 1 1]
[0 1 1]
[0 0 1]


It's harder to get a matrix with entries True or False.

more