python列主矩阵和行主矩阵

2024-10-05 19:35:42 发布

您现在位置:Python中文网/ 问答频道 /正文

如何得到矩阵元素的一维索引?在

例如:

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.
        """

Tags: the函数元素defnporder矩阵数组
2条回答

np.ravel_multi_index使用指定order的选项将n-d索引转换为平面索引:

In [152]: np.ravel_multi_index((0,2),(2,3),order='C')                           
Out[152]: 2
In [153]: c[0,2], c.flat[2]                                                     
Out[153]: (5, 5)

应用于order='F'的情况有点棘手:

^{pr2}$

[1,2]元素在两个顺序中是相同的,最后一个是“6”。在

与@Divakar的例子比较:

In [160]: np.ravel_multi_index([1,1],[2,3],order='C')                           
Out[160]: 4
In [161]: np.ravel_multi_index([1,1],[2,3],order='F')                           
Out[161]: 3

只需按列数缩放行索引并为行主顺序添加列索引。对于列主顺序,请使用行数来缩放行索引并再次添加列索引。在

因此,要获得rowmaj版本的扁平化索引-

i*n+j

要获取colmaj版本的展平索引-

^{pr2}$

其中:

i = row index
j = col index
m = number of rows in the matrix
n = number of columns in the matrix

放入函数格式-

def linearize(i, j, m, n, order='C'):
    if order=='C': # rowmaj
        return i*n+j
    elif order=='F': # colmaj
        return i*m+j
    else:
        raise Exception("Invalid order value")

样本运行-

In [42]: linearize(i=1, j=1, m=2, n=3, order='C')
Out[42]: 4 # element : 5 in rowmaj array, d

In [43]: linearize(i=1, j=1, m=2, n=3, order='F')
Out[43]: 3 # element : 4 in colmaj array, c

相关问题 更多 >