如何得到矩阵元素的一维索引?在
例如:
b=np.array([1, 2, 3, 4, 5, 6])
c = b.reshape(2,3,order='F')#colmaj
d = b.reshape(2,3)#rowmaj
这是c:
^{pr2}$这是d:
([[1, 2, 3],
[4, 5, 6]])
如果我使用c[1,2],我得到元素6,我需要得到一维数组的索引,即5。我可以在精神上这样做,但如果我有一个大矩阵,需要随机选择一个元素,我将无法。我需要为colmajor和rowmajor矩阵编写函数。在
def linearize_colmajor(i, j, m, n):
"""
Returns the linear index for the `(i, j)` entry of
an `m`-by-`n` matrix stored in column-major order.
"""
np.ravel_multi_index
使用指定order
的选项将n-d索引转换为平面索引:应用于
^{pr2}$order='F'
的情况有点棘手:[1,2]
元素在两个顺序中是相同的,最后一个是“6”。在与@Divakar的例子比较:
只需按列数缩放行索引并为行主顺序添加列索引。对于列主顺序,请使用行数来缩放行索引并再次添加列索引。在
因此,要获得
rowmaj
版本的扁平化索引-要获取
^{pr2}$colmaj
版本的展平索引-其中:
放入函数格式-
样本运行-
相关问题 更多 >
编程相关推荐