Home > other >  how to use np.ix_ to execute 4 by 4 matrix operations ? i have to insert a small (4 by 4) matrix in
how to use np.ix_ to execute 4 by 4 matrix operations ? i have to insert a small (4 by 4) matrix in

Time:11-29

how to do the matrix operations, so that it can produce results something like this:

4 by 4 matrix insertion into big matrix

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_.

  • Related