2
votes

I have a matrix A and a vector b. I don't know their sizes, the size varies because it is the output of another function. What I want to do is filter A by a column (let's say jth column) which has at least one value that is in b.

How do I do this without measuring the size of b and concatenating every filtered result. Right now, the code is like this (assume j is a given value)

bsize=size(b,1);
for i=1:bsize
    if i==1
        a=A(A(:,j)==b(i),:);
    else
        a=[a; A(A(:,j)==b(i),:)];
    end
end

I want to code a faster solution.

I am adding a numerical example just to make it clear. Let's say

A=[2  4
   7 14
  11 13
  15 14]

and b=[4 14]

What I'm trying to do is filter to obtain the A matrix whose values are 4 and 14 in the second column, the elements of b to obtain the following output.

A=[2  4
   7 14
  15 14]

In my data A has more than 12000 rows and b has more than 100 elements. It doesn't always have to be the second column, sometimes the column index changes but that's not the problem now.

1
I'm having a difficult time understanding what your objective is. Can you show us a numerical example and expected output? - rayryeng
@rayreng Thank you. I added a small example - A Doe

1 Answers

2
votes

Use the ismember function to create a logical index based on column j=2 of A and vector b, and use that index into the rows of A:

output = A(ismember(A(:,j), b), :);