ind2sub函数可以用来把矩阵元素的index转换成对应的下标(determines the equivalent subscript values corresponding to a single index into an array)
例如: 一个4*5的矩阵A,第2行第2个元素的index的6(matlab中matrix是按列顺序排列),可以用ind2sub函数来计算这个元素的下标 [I,J] = ind2sub(size(A),6)
[I,J] = ind2sub(siz,IND) returns the matrices I and J containing the equivalent row and column subscripts corresponding to each linear index in the matrixIND for a matrix of size siz. siz is a vector with ndim(A) elements (in this case, 2), wheresiz(1) is the number of rows andsiz(2) is the number of columns.
例子:For matrices, [I,J] = ind2sub(size(A),find(A>5)) returns the same values as[I,J] = find(A>5).
在命令窗口输入:
>> A=[4 7 2 9 8;3 9 1 4 3;1 5 9 6 4;8 3 7 1 0]
A =
4 7 2 9 8
3 9 1 4 3
1 5 9 6 4
8 3 7 1 0
则A中每个元素对应的索引如下(MATLAB中数据是按列的方式存储的):
1 5 9 13 17
2 6 10 14 18
3 7 11 15 19
4 8 12 16 20
ind=sub2ind(siz,I,J):siz表示要转换的矩阵的行列数,I是要转换矩阵的行标,J是要转换矩阵的列标。I,J的行列数必须相同。ind为输出参数,其行列数与I,J相同。ind即为索引。
在命令窗口中输入:
>> ind=sub2ind(size(A),[1,2;3,4],[1,1;2,2])
则显示
ind =
1 2
7 8
从运算结果可以看出,在矩阵A中,下标(1,1)的索引值为1,下标(2,1)的索引值为2,下标(3,2)的索引值为7,下标(4,2)的索引值为8
Like this:
Like Loading...
Related