Samo Jerom
Samo Jerom

Reputation: 2371

How to extract values from a Matrix that recorded in a vector?

Just came across this problem might be interesting in many applications, for example,

I have a vector A = [2; 5; 10], the values in vector A is sorted and unique.

I have got a matrix (2D or 3D), for example, B = [2, 8, 10; 2, 5, 5; 9, 1, 10];

Want to get a matrix C = [1, 0, 1; 1, 1, 1; 0, 0, 1].

It means if the element in B is also an element of A, we set it to one; otherwise, set the value to zero.

I did this in a for-loop, but for a large 3D matrix, it takes a long time to finish the loop.

Just wondering if there is a smarter method to do this without 'for' loop.

C = zeros(size(B));
for i = 1:size(A,1)
    a = A(i);
    C(B==a) = 1;  
end

Upvotes: 0

Views: 50

Answers (1)

Stewie Griffin
Stewie Griffin

Reputation: 14939

This is exactly what ismember does:

A = [2; 5; 10];
B = [2, 8, 10; 2, 5, 5; 9, 1, 10];
C = ismember(B,A)

C =

     1     0     1
     1     1     1
     0     0     1

From the documentation:

ismember(A,B) returns an array containing 1 (true) where the data in A is found in B. Elsewhere, it returns 0 (false).

Upvotes: 4

Related Questions