MATLAB: How to intersect a matrix with a set and keep the rows of the matrix

by rowintersectionmatrix

I'm trying to intersect an N by M matrix, 'A', with a set (a 1 by X matrix), 'B', but am trying to do so by rows. (e.g. A(1:M) intersect B ).
So I would end up with an N by '__' matrix where the rows are the intersection of the respective row and set 'B', rather than a large set.
Is there a way to do this without using a for loop?

Best Answer

If you only want to get the min and max of each row, and really want to avoid for loops, here's a solution. This gives the min and max for each row of A, ignoring values not in B, which is I think what you are looking for.
A = [...
2 12 6 4 8
1 3 5 7 9
];
B = [ 1 2 3 4 5 6 ];
tf = ismember(A, B);
Amax = A;
Amin = A;
Amax(~tf) = -Inf;
Amin(~tf) = Inf;
maxval = max(Amax, [], 2);
minval = min(Amin, [], 2);
results
>> maxval
maxval =
6
5
>> minval
minval =
2
1