dcwang
dcwang

Reputation: 13

find in multidimensional array - MATLAB

I have a 3 by 3 by 2 by 3 array X containing 1s or 0s. Picture this as a row of three 3 by 3 matrices along a row and another such 'layer' behind them (from the '2').

I want to find the positions in X of the 0s in the first layer and second layer separately. I'm not really sure how to do this with find, but heuristically something like:

A = find(X == 0 & 3rd index of X is 1) 

B = find(X == 0 & 3rd index of X is 2)

EDIT

I just realised my attempt to simplify my actual question made it misleading. The array X actually has -1's, 1's and -2's and I want to find the -2's. They're not meant to be logical operators. Also I would prefer any operation proposed to be as fast as possible as this will be part of a recursive backtracking algorithm.

Upvotes: 0

Views: 521

Answers (2)

Daniel
Daniel

Reputation: 36720

solution using logical indexing

I recommend to use logical indexing instead of find. This gives you all indices where X is 1

value_you_want=-2
C=X==value_you_want;

Now you want only parts of these indices in A and B, first initialize A and B with false of the same size as C:

A=false(size(C));
B=A;

And finally copy the slice you want to each of these matrices:

A(:,:,1,:)=C(:,:,1,:);
B(:,:,2,:)=C(:,:,2,:);

If you really want your numeric indices, use find(A) and find(B)


Alternative solution using linear indices and find

%get all indices
C=find(X==value_you_want)
%convert linear indices to subscript indices, only use third dimension
[~,~,S,~]=ind2sub(size(X),find(X==0));
%Use S to split C
A=C(S==1);
B=C(S==2);

Upvotes: 2

aybassiouny
aybassiouny

Reputation: 578

Generally use find(condition) to return linear indices in the array satisfying condition.

A = find(A(:,:,1,:)<1)

B = find(A(:,:,2,:)<1)

Upvotes: 0

Related Questions