【问题标题】:Creating a matrix where each element is equal to the minimum of its row and column index创建一个矩阵,其中每个元素都等于其行和列索引的最小值
【发布时间】:2018-03-20 22:17:35
【问题描述】:

我想创建一个矩阵 C,其中每个元素都等于其相应行和列索引的最小值。例如:第一行第二列对应的元素取值为1,第八行第三列对应的元素取值为3等。

我编写了以下代码,可以返回我想要的内容。运行以下代码:

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)

结果

[[  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.]]

问题:这是最有效的方法吗?如果不;如何改进这种方法?

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    选项 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]])
    

    选项 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]])
    

    【讨论】:

      【解决方案2】:

      另一种方法是对每列包含所有 1 的上三角矩阵求和:

      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.]])
      

      显然不如mgrid 方法有效,但我认为这是一个不错的选择。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-07
        • 2021-11-18
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        • 2011-09-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多