简体   繁体   中英

Creating a matrix where each element is equal to the minimum of its row and column index

I want to create a matrix C where each element is equal to the minimum of its corresponding row and column index. For example: the element corresponding to the first row and second column should have a value of 1, the element corresponding to the eighth row and the third columns should have a value of 3, etc.

I have written the following code that returns to me what I want. Running the following code:

from numpy import empty

C = empty(shape=(32,32))

for j in range(1,33):
    for i in range(1,33):
        minimum = min(i,j)
        C[i-1][j-1] = minimum

print(C)

Results in

[[  1.   1.   1. ...,   1.   1.   1.]
 [  1.   2.   2. ...,   2.   2.   2.]
 [  1.   2.   3. ...,   3.   3.   3.]
 ..., 
 [  1.   2.   3. ...,  30.  30.  30.]
 [  1.   2.   3. ...,  30.  31.  31.]
 [  1.   2.   3. ...,  30.  31.  32.]]

Question: Is this the most efficient way of doing this? If not; how can this method be improved?

Option 1
np.mgrid

np.mgrid[1:33, 1:33].min(axis=0)

array([[ 1,  1,  1, ...,  1,  1,  1],
       [ 1,  2,  2, ...,  2,  2,  2],
       [ 1,  2,  3, ...,  3,  3,  3],
       ...,
       [ 1,  2,  3, ..., 30, 30, 30],
       [ 1,  2,  3, ..., 30, 31, 31],
       [ 1,  2,  3, ..., 30, 31, 32]])

Option 2
np.indices

(np.indices((32, 32)) + 1).min(axis=0)

array([[ 1,  1,  1, ...,  1,  1,  1],
       [ 1,  2,  2, ...,  2,  2,  2],
       [ 1,  2,  3, ...,  3,  3,  3],
       ...,
       [ 1,  2,  3, ..., 30, 30, 30],
       [ 1,  2,  3, ..., 30, 31, 31],
       [ 1,  2,  3, ..., 30, 31, 32]])

Another way would be to perform a cumulative sum of an upper-triangular matrix that contains all 1s along each column:

In [16]: np.cumsum(np.triu(np.ones((32,32))), axis=0)
Out[16]:
array([[  1.,   1.,   1., ...,   1.,   1.,   1.],
       [  1.,   2.,   2., ...,   2.,   2.,   2.],
       [  1.,   2.,   3., ...,   3.,   3.,   3.],
       ...,
       [  1.,   2.,   3., ...,  30.,  30.,  30.],
       [  1.,   2.,   3., ...,  30.,  31.,  31.],
       [  1.,   2.,   3., ...,  30.,  31.,  32.]])

Obviously not as efficient as a mgrid approach, but I figure it's a fancy alternative.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM