Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Say I have the following:

  • Data matrix M (m-by-n);
  • Matching row V (1-by-n);
  • Matching positions I (1-by-n logical);

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,:);
like image 874
Pranasas Avatar asked May 18 '15 09:05

Pranasas


1 Answers

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
like image 145
Luis Mendo Avatar answered Nov 15 '22 05:11

Luis Mendo