MATLAB: Looping each row from one matrix to the other matrix

for loopindexingismemberMATLAB

Hi.
I have two matrix with unique rows. Matrix A (228 x 9) and B(256 x 9) in one way or another have exact matching rows. I want to find the index where each row of B is a match of any row in A and store a new variable C (where all the indices are found). I tried matching manually per row of B against A. But it's taking me so long. I tried using for loop but I can't seem to figure out with ismember function.
Here's how I did it with single row from B.
[lia, locb] = ismember(A, B(1,:), 'rows'); % starting off from row 1.
Any help would be appreciated.
Cheers

Best Answer

You were close. Instead of referencing only 1 row of B, reference the entire matrix.
[lia, locb] = ismember(A, B, 'rows');
Example
A = reshape(1:20,4,5);
B = A([3,1,4],:); % B is a version of A with scattered rows and 1 row missing.
% >> A
% A =
% 1 5 9 13 17

% 2 6 10 14 18
% 3 7 11 15 19

% 4 8 12 16 20

% >> B
% B =
% 3 7 11 15 19
% 1 5 9 13 17
% 4 8 12 16 20
[lia, locb] = ismember(A, B, 'rows')
% lia =
% 4×1 logical array
% 1


% 0
% 1
% 1
% locb =
% 2
% 0
% 1
% 3
We can see that row 2 of A is not in B since lia(2)==0 and locb(2)==0.
We can also see that row 1 of A is in row 2 of B since locb(1)==2.