tmo
tmo

Reputation: 1543

Logical Indexing of 3D matrix on basis of a 1D matrix

I have a 450-by-1000-by-3 double in Matlab, which consists of 19 unique values that are obviously repeated a lot of times. Let's call this A.

Let's pretend that some of these numbers are 10, 20 and 30. I store those numbers in B, such that B is 3-by-1.

Now, I really, really would like to spit out a new matrix with the same dimensions as A (450-by-1000-by-3) but with 1 where I find 10, 20 and 30, and 0 where it differs from these 3 numbers.

I've looked into both logical indexing and find, but I keep banging my head against the wall. Doing this with one number is easy, but doing it with an array somehow does not seem to work. Even with a loop.

Upvotes: 0

Views: 177

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

Approach 1: use ismember, as suggested by Dan:

result = ismember(A, B);

Approach 2: use bsxfun:

result = any(bsxfun(@eq, A, reshape(B,1,1,1,[])), 4);

Upvotes: 2

Related Questions