5.10) Finding elements in arrays
find is a very useful function for finding the indices (and hence the values) of array elements you are interested in.
- In its most basic form, it finds the indices of non-zero elements in an array
- In combination with a logical condition, it finds the indices of elements that satisfy the condition.
- Syntax:
[matlab]
>> [z]=find(X); % z is the linear indices where X is non-zero.
[/matlab]
[matlab]
>> [x y]=find(X); % If X is a matrix, "find" can return
>> % the row and column subscripts of all cells that are non-zero.
[/matlab]
[matlab]
>> [x y v]=find(X); % If X is a matrix, "x" and "y" will get
>> % the row and column subscripts of all cells that are non-zero,
>> % and "v" will get the actual values.
[/matlab]
In all cases, "X" can also be a logical function of X:
[matlab] >> A=magic(4); >> [x y]=find(A>12) x= 1 y= 1 4 2 4 3 1 4 >> z=find(A>12); >> % Linear indices >> A(z)= 16 14 15 13 >> % These are the indices >> % where A > 12. [/matlab] |
[matlab] >> A=magic(5); >> B=eye(5); >> z=find((B==1)&(A>10)) >> A(z)= 17 13 21 >> % These are indices where >> % A>10 and B==1 [/matlab] |