Reputation: 1591
Suppose that:
A = [1,22,33; 2,44,55; 2,66,77]
id = [2 3 5]
I am trying to select all the matrix A
rows if the value of their first column appears in id
at least once, without using a loop.
Hence, starting from:
A =
1 22 33
2 44 55
2 66 77
in this example I would like to get the following:
2 44 55
2 66 77
what is the easier way to do this? Many thanks.
Upvotes: 2
Views: 32
Reputation: 112749
Use ismember
to create a logical index that will select the rows:
A(ismember(A(:,1), id),:)
Alternatively, you can use any
and bsxfun(@eq, ...)
instead of ismember
:
A(any(bsxfun(@eq, A(:,1).', id(:)), 1), :)
Or, starting at Matlab version R2016b, you can replace bsxfun(@eq, ...)
by just ==
thanks to implicit singleton expansion:
A(any(A(:,1).'==id(:), 1), :)
Upvotes: 4