python列主要和行主要矩阵

时间:2019-02-28 19:15:09

标签: python numpy matrix

我如何获得矩阵元素的一维索引?

例如:

b=np.array([1, 2, 3, 4, 5, 6])
c = b.reshape(2,3,order='F')#colmaj
d = b.reshape(2,3)#rowmaj

这是c:

([[1, 3, 5],
 [2, 4, 6]])

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

2 个答案:

答案 0 :(得分:1)

只需按列数缩放行索引,然后为行优先顺序添加列索引。对于大订单,请使用行数来缩放行索引并再次添加列索引。

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

i*n+j

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

i*m+j

其中:

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

答案 1 :(得分:0)

np.ravel_multi_index将n-d索引转换为平面索引,并可以选择指定order

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'案例的应用有点棘手:

In [154]: np.ravel_multi_index([0,2],[2,3],order='F')                           
Out[154]: 4
In [155]: d[0,2], d.flat[4], d.ravel(order='F')[4]                              
Out[155]: (3, 5, 3)
In [156]: d.ravel()                                                             
Out[156]: array([1, 2, 3, 4, 5, 6])
In [157]: d.ravel(order='F')                                                    
Out[157]: array([1, 4, 2, 5, 3, 6])

[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
相关问题