开发者

MATLAB: Finding coordinates of value in multidimensional array

I have a three-dimensional array, and I'd like to be able to find a specific value and get the three coordinates.

For example, if I have:

A = [2 4 6; 8 10 12]

A(:,:,2) = [5 7 9; 11 13 15]

and I want to find开发者_开发知识库 where 7 is, I'd like to get the coordinates i = 1 j = 2 k = 2

I've tried variations of find(A == 7), but I haven't got anywhere yet.

Thanks!


The function you seek is ind2sub:

[i,j,k]=ind2sub(size(A), find(A==7))
i =
     1
j =
     2
k =
     2


You can use find to locate nonzero elements in an array, but it requires a little bit of arithmetic. From the documentation:

[row,col] = find(X, ...) returns the row and column indices of the nonzero entries in the matrix X. This syntax is especially useful when working with sparse matrices. If X is an N-dimensional array with N > 2, col contains linear indices for the columns. For example, for a 5-by-7-by-3 array X with a nonzero element at X(4,2,3), find returns 4 in row and 16 in col. That is, (7 columns in page 1) + (7 columns in page 2) + (2 columns in page 3) = 16.

If the matrix M has dimensions a x b x c, then the indices (i,j,k) for some value x are:

[row,col] = find(A==x);
i = row;
j = mod(col,b);
k = ceil(col/b);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜