Say I have the following:
I want to filter all rows of M that have the same values as V at the matching positions I. I believe that Matlab indexing if powerful enough to do that without loops. But how?
Current solution: run though all the columns and update the filtered row positions F (m-by-1 logical).
F = true(m,1);
for k = 1:n;
if I(k);
F = F & (M(:,k)==V(k));
end;
end;
M = M(F,:);
Here's one way:
result = M(all(bsxfun(@eq, M(:,I), V(I)), 2), :);
How it works
Each row of M(:,I)
is compared element-wise with the row vector V(I)
using bsxfun
. Rows for which all
columns match are selected. The resulting logical vector is used to index the rows of M
.
Example
M = [ 8 3 6 9
5 4 9 8
8 9 6 9 ];
I = [ true false true true ];
V = [ 8 1 6 9 ];
>> result = M(all(bsxfun(@eq, M(:,I), V(I)), 2), :)
result =
8 3 6 9
8 9 6 9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With