Create a numpy matrix with elements as a function of indices

前端 未结 5 922
迷失自我
迷失自我 2020-12-16 21:11

How can I create a numpy matrix with its elements being a function of its indices? For example, a multiplication table: a[i,j] = i*j

An Un-numpy and un-

5条回答
  •  再見小時候
    2020-12-16 21:38

    Just wanted to add that @Senderle's response can be generalized for any function and dimension:

    dims = (3,3,3) #i,j,k
    ii = np.indices(dims)
    

    You could then calculate a[i,j,k] = i*j*k as

    a = np.prod(ii,axis=0)
    

    or a[i,j,k] = (i-1)*j*k:

    a = (ii[0,...]-1)*ii[1,...]*ii[2,...]
    

    etc

提交回复
热议问题