Suppose that I
and J
are column vectors, (both of length K, say), such that for valid index k, the k-th entries of I
and J
represent row and column coordinates in some N-by-N matrix MAT
.
假设I和J都是列向量(都是长度为K的),对于有效的索引K, I和J的第K个元素表示某个n×n矩阵的行和列坐标。
With MATLAB, to assign to the positions in MAT
with coordinates corresponding to the positions specified by I
and J
, one can write:
使用MATLAB,将MAT中与I、J指定的位置对应的坐标赋值为:
MAT(sub2ind([N N], I, J)) = X;
...where X
is some vector having length K.
…X是某个长度为K的向量。
With numpy, the best I can come up with is
有了numpy,我能想到的最好的就是
MAT.flat[[np.ravel_multi_index((I[k], J[k]), (N, N)) for k in range(K)]] = X
Is there more "colloquial numpy" way to this?
还有什么“口语麻木”的方法吗?
1 个解决方案
#1
4
It is much easier than that with numpy.
这比麻木要容易得多。
i = I.ravel()
j = J.ravel()
MAT[i,j] = X
I used the ravel
method to convert the columns into one-dimensional arrays. An alternative is
我使用ravel方法将列转换为一维数组。另一种方法是
MAT[I.flat, J.flat] = X
I can't say for sure without seeing the full context, but I suspect you could modify the code that creates I
and J
to make them one-dimensional arrays (i.e. with shape (K,)
) instead of columns with shape (K, 1)
. If you did that, you could just write
我不能肯定地说,没有看到完整的上下文,但是我怀疑您可以修改创建I和J的代码,使它们成为一维数组(即,有形状(K,))而不是有形状的列(K, 1)。如果您这样做了,您可以直接编写。
MAT[I,J] = X
#1
4
It is much easier than that with numpy.
这比麻木要容易得多。
i = I.ravel()
j = J.ravel()
MAT[i,j] = X
I used the ravel
method to convert the columns into one-dimensional arrays. An alternative is
我使用ravel方法将列转换为一维数组。另一种方法是
MAT[I.flat, J.flat] = X
I can't say for sure without seeing the full context, but I suspect you could modify the code that creates I
and J
to make them one-dimensional arrays (i.e. with shape (K,)
) instead of columns with shape (K, 1)
. If you did that, you could just write
我不能肯定地说,没有看到完整的上下文,但是我怀疑您可以修改创建I和J的代码,使它们成为一维数组(即,有形状(K,))而不是有形状的列(K, 1)。如果您这样做了,您可以直接编写。
MAT[I,J] = X