1

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.

Divakar
  • 218,885
  • 19
  • 262
  • 358
user42527
  • 21
  • 2

1 Answers1

4

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
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • 2
    Thank you for this wonderful `bsxfun` tutorial sensei ;). Can you elaborate on the `[3 2 1]` within the `permute`? I think I get the rest. – Adriaan Sep 15 '15 at 17:46
  • @Adriaan That "sends" `Z` to the third dimension, so that eXpansion with `bsxfun` could take place. Sort of like in [`this case`](http://stackoverflow.com/questions/23807960/bsxfun-implementation-in-matrix-multiplication/23808285#23808285). – Divakar Sep 15 '15 at 17:59
  • Thank you for you response but I misspecified my question. I actually want to know the indices of Z for which Z and each row of A have common values. So I want the solution based on your example to be 4 x 7 – user42527 Sep 15 '15 at 18:01
  • @user42527 This `squeeze(any(bsxfun(@eq,A,permute(Z(:),[3 2 1])),2))` should work then. Edited answer with it. – Divakar Sep 15 '15 at 18:03