how to do the matrix operations, so that it can produce results something like this:
first matrix shown in the image is wrong output and the second matrix (below) is the expected output
I found that it can be done using np.ix_, but i'm not able to apply it.
thankyou.
CodePudding user response:
What's so puzzling about using np.ix_
?
In [529]: res = np.zeros((10,10),int)
In [530]: res[np.ix_([1,7],[1,9])]=[[1,1],[1,-1]]
In [531]: res
Out[531]:
array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 1, 0, 0, 0, 0, 0, 0, 0, 1],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 1, 0, 0, 0, 0, 0, 0, 0, -1],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
The same indexing can be used to select the nonzero values:
In [532]: res[np.ix_([1,7],[1,9])]
Out[532]:
array([[ 1, 1],
[ 1, -1]])
OK, I'm inserting a (2,2) array because those are the obvious nonzero values. For any other, just adjust the two lists/arrays provided to ix_
.