7

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!

2 Answers 2

12

The function you seek is ind2sub:

[i,j,k]=ind2sub(size(A), find(A==7))
i =
     1
j =
     2
k =
     2
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.