Issue
Problem Description
I have a NumPy matrix M
generated as follows: M = np.arange(25).reshape(-1, 5) * 10
. I'm trying to create custom output lists based on this matrix for different values of i
. The desired output for various values of i
is as follows:
- For
i=5
, the output should be[10, 20, 30, 40, 70, 80, 90, 130, 140, 190]
. - For
i=4
, the output should be[10, 20, 30, 0, 70, 80, 0, 130, 0, 0]
. - For
i=3
, the output should be[10, 20, 0, 0, 70, 0, 0, 0, 0, 0]
. - For
i=2
, the output should be[10, 0, 0, 0, 0, 0, 0, 0, 0, 0]
.
I'm struggling to find an efficient way to achieve this. Can someone please help me with a Python code snippet that can generate these custom output lists based on the matrix M
and the specified values of i
? Thank you!
M.ravel()[np.flatnonzero(np.triu(M, k=1))]
for i=5
Solution
Make the array:
In [134]: M=np.arange(25).reshape(5,5)*10
and the triu indices:
In [135]: idx = np.triu_indices(5,k=1);idx
Out[135]: (array([0, 0, 0, 0, 1, 1, 1, 2, 2, 3]), array([1, 2, 3, 4, 2, 3, 4, 3, 4, 4]))
for i=5:
In [136]: M[idx]
Out[136]: array([ 10, 20, 30, 40, 70, 80, 90, 130, 140, 190])
zero out a column, and repeat:
In [139]: M[:,-1:]=0; M
Out[139]:
array([[ 0, 10, 20, 30, 0],
[ 50, 60, 70, 80, 0],
[100, 110, 120, 130, 0],
[150, 160, 170, 180, 0],
[200, 210, 220, 230, 0]])
In [140]: M[idx]
Out[140]: array([ 10, 20, 30, 0, 70, 80, 0, 130, 0, 0])
and so on:
In [141]: M[:,-2:]=0; M[idx]
Out[141]: array([10, 20, 0, 0, 70, 0, 0, 0, 0, 0])
In [142]: M[:,-3:]=0; M[idx]
Out[142]: array([10, 0, 0, 0, 0, 0, 0, 0, 0, 0])
Answered By - hpaulj
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.