user42527
user42527

Reputation: 21

Can I find common values between each row of a matlab matrix and a vector without a loop?

I have a matrix A = [a X b] and a vector Z = [1 X z], where z > b.

I want to find the indices of matrix A for which Z and each row of the matrix A have the same value. I know I can do this by applying ismember to each row of A, but I would to find a faster solution without using a for loop.

Upvotes: 1

Views: 47

Answers (1)

Divakar
Divakar

Reputation: 221514

Let's bsxfun it -

squeeze(any(bsxfun(@eq,A,permute(Z(:),[3 2 1])),2))

Or

any(bsxfun(@eq,permute(A,[1 3 2]),Z(:).'),3)

Verify results with a sample run -

>> A
A =
     3     9     3     1     6
     4     9     4     2     5
     1     6     8     6     5
     2     1     1     7     3
>> Z
Z =
     7     2     7     2     4     6     8
>> for ii = 1:size(A,1)
    out_loopy(ii,:) = ismember(Z,A(ii,:));
end
>> out_loopy
out_loopy =
     0     0     0     0     0     1     0
     0     1     0     1     1     0     0
     0     0     0     0     0     1     1
     1     1     1     1     0     0     0
>> squeeze(any(bsxfun(@eq,A,permute(Z(:),[3 2 1])),2))
ans =
     0     0     0     0     0     1     0
     0     1     0     1     1     0     0
     0     0     0     0     0     1     1
     1     1     1     1     0     0     0
>> any(bsxfun(@eq,permute(A,[1 3 2]),Z(:).'),3)
ans =
     0     0     0     0     0     1     0
     0     1     0     1     1     0     0
     0     0     0     0     0     1     1
     1     1     1     1     0     0     0

Upvotes: 4

Related Questions