Pranasas
Pranasas

Reputation: 596

Filter matrix by multiple column values w/o loops (Matlab)?

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,:);

Upvotes: 6

Views: 598

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112769

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

Upvotes: 3

Related Questions