Ask Your Question
0

matrix entry-wise comparison (masking)

asked 2012-11-20 13:43:49 +0200

shacsmuggler gravatar image

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

3 Answers

Sort by ยป oldest newest most voted
3

answered 2012-11-20 15:18:41 +0200

DSM gravatar image

updated 2012-11-20 18:32:17 +0200

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)
edit flag offensive delete link more
0

answered 2012-11-20 15:49:15 +0200

shacsmuggler gravatar image

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]])
edit flag offensive delete link more
0

answered 2012-11-20 14:24:06 +0200

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.

edit flag offensive delete link more

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: 2012-11-20 13:43:49 +0200

Seen: 658 times

Last updated: Nov 20 '12