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

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

 Akzeptierte Antwort

Andrei Bobrov
Andrei Bobrov am 27 Jul. 2016
Bearbeitet: Andrei Bobrov am 27 Jul. 2016
[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,:);

2 Kommentare

Thank you Andrei. That worked perfectly. It's the first time I've worked on a large dataset and I'm quickly realising the impracticality of loops!
Out of interest, can this problem be handled using the 'intersect' function as well? I spent a bit of time looking at it this evening but couldn't figure out a solution.
Thank you once again.
yes, only for case from your example:
[~,ia,ib] = intersect(A(:,1:2),B(:,1:2),'rows');
B(ib,:) = A(ia,:)
best variant - use ismember:
A = [10 11 3 4
12 11 4 6
13 13 2 8]
B = [12 11 NaN NaN
10 11 NaN NaN
12 11 NaN NaN
13 11 NaN NaN]
[lo,ii] = ismember(B(:,1:2),A(:,1:2),'rows');
B(lo,:) = A(ii(lo),:)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and Arrays finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by