(一)Matlab中sub2ind函数
1、sub2ind函数的功能
将下标转换为线性索引。
2、sub2ind函数的语法
有以下两种形式
(1)ind = sub2ind(sz, row, col)
(2)ind = sub2ind(sz, I1, I2,…,In)
本文主要对第一种形式进行python实现。
3、sub2ind函数的参数说明
输入参数:
sz - 数组的大小(正整数向量)
数组的大小,指定为正整数向量。此向量的每个元素指示对应维度的大小。例如,[2 3 4] 定义 2×3×4 数组。
数据类型: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64
row - 行下标 (标量|向量|矩阵|多维数组)
行下标,指定为标量、向量、矩阵或多维数组。row 的大小必须与 col 的大小相同。
数据类型: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64
col - 列下标 (标量|向量|矩阵|多维数组)
列下标,指定为标量、向量、矩阵或多维数组。col 的大小必须与 row 的大小相同。
数据类型: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64
I1, I2,…,In - 多维下标(标量|向量|矩阵|多维数组)
多维下标,指定为标量、向量、矩阵或多维数组。每个数组 I1,I2,…,In 必须具有相同的大小。
数据类型: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64
输出参数:
ind - 线性索引(标量 |向量|矩阵|多维数组)
线性索引,指定为标量、向量、矩阵或多维数组。ind 的大小与输入 row、col 或 I1,I2,…,In 的大小相同。
数据类型: double
4、sub2ind函数说明
(1)ind = sub2ind(sz, row, col):针对大小为sz的矩阵返回由row和col指定的行列下标的对应线性索引ind。此处,sz是包含两个元素的向量,其中sz(1)指定行数,sz(2)指定列数。
(2)ind = sub2ind(sz, I1, I2,…,In):针对大小为sz的多维数组返回由n个数组I1, I2,…,In指定的多维下标的对应线性索引ind。此处,sz是包含n个元素的向量,用于指定每个数组维度的大小。
5、sub2ind函数示例
3x3的矩阵从下标到线性索引的映射如下所示。
(1)在3*3矩阵中指定行下标和列下标,将下标转换为线性索引。
>> row = [1 2 3 1];
>> col = [2 2 2 3];
>> sz = [3 3];
>> ind = sub2ind(sz, row, col)
ind =
4 5 6 7
(2)将下标转换为三维数组的线性索引
2x2x2的数组从下标到线性索引的映射如下所示。
在2x2x2数组中指定行下标,列下标和页下标,将下标转换为线性索引。
>> I1 = [1 2 1 2];
>> I2 = [2 2 1 1];
>> I3 = [1 1 2 2];
>> sz = [2 2 2];
>> ind = sub2ind(sz, I1, I2, I3)
ind =
3 4 5 6
(二)使用Python实现sub2ind函数
在将Matlab的sub2ind函数改写成Python的过程中遇到了很多问题,查看相关资料,可以从Python中的ravel_multi_index函数的功能着手进行深入了解。
1、重点说明
(i)Python中下标是以 0 作为开始的;
(ii)在numpy中,访问的以行为主的元素,而不是以列为主元素;
也就是说,
在Matlab中的索引矩阵为:
1 4 7
Matlab_ind = 2 5 8 以列为主进行索引排序的。
3 6 9
0 1 2
Python_ind = 3 4 5 以行为主进行索引排序的。
6 7 8
2、详细代码展示
def col_sub2ind(array_shape, rows, cols):
ind = rows + cols*array_shape[0]
if ind < 0:
ind = -1
print("Index Value ERROR!")
elif ind >= array_shape[0]*array_shape[1]:
ind = -1
print("Index Value OVERFLOW!")
else:
return ind
3、参数说明
array_shape:可使用array.shape;
rows:数组的行数;
cols:数组的列数;
4、示例
import numpy as np
# define a numpy array A
A = np.array([[1, 2, 3], [2, 9, 8], [5, 6, 7]])
print(A)
[[1 2 3]
[2 9 8]
[5 6 7]]
ind = col_sub2ind(A.shape, 2, 1)
print("ind = ", ind)
ind = 5
【注意】:ind的值为对应位置的索引值,不是数组中的元素值。
剖析:
数组A ————————>数组A对应的索引ind
1 2 3 ——————————> 0 3 6
2 9 8 ——————————> 1 4 7
5 6 7 ——————————> 2 5 8
因此当调用函数col_sub2ind(A.shape, 2, 1),即想要获取数组A第2行,第1列元素A[2, 1] = 6的索引值时,ind = 5。
至此,我们就得到了numpy数组一列为主进行排序的对应位置的索引值。
PS:但是,该方法只是实现了给出一个对应行、列元素的索引值,Matlab中该函数可以同时得到多个元素位置的索引值,因此,col_sub2ind 函数还需要继续优化,只是,能够满足目前项目的要求。