MATLAB: Efficient method for populating a matrix based on its equality with another matrix

for loopintersectmatrix arraymatrix manipulationsortvectorization

Hello. I'm having a problem populating a matrix and would greatly appreciate some help.
If we have:
if true
A = 10 11 3 4 B = 10 11 NaN NaN
12 11 4 6 12 11 NaN NaN
13 13 2 8 13 11 NaN NaN
end
What I want is the following: if A(i,1:2) and B(i,1:2) are the same, then B(i,3:4) = A(i,3:4). So something like this:
if true
B = 10 11 3 4
12 11 4 6
13 11 NaN NaN
end
I've managed to create a loop that achieves this result. Which is the following:
if true
for i = 1:length(B);
for j = 1:length(A);
if B(i,1) == A(j,1) && B(i,2) == A(j,2);
B(i,3) = A(j,3);
end
end
end
end
The problem is, the two arrays I'm working with have close to 3 million rows so a double conditioned loop is extremely slow. Is there a vectorised way to achieve the same result that is significantly quicker?
Any help would be greatly appreciated.
Thanks
Andrew

Best Answer

[lo,ii] = ismember(A(:,1:2),B(:,1:2),'rows');
B(ii(lo),:) = A(lo,:);
or
lo = all(A(:,1:2) == B(:,1:2),2);
B(lo,:) = A(lo,:);