Compare two matrices of different dimensions

I have two matrices A=500000*4 and B=4300000*4.
Matrix A = id, plus 3 columns of NaN.
Matrix B = id, lat, lon, elev.
I would like to find the id values in A = B, and based on those same id values, fill matrix A with the missing lat,lon,elev.
The code I have is:
for i=1:length(A)
ind = B(:,1)==A(i,1);
A(i,2:4) = B(ind,2:4);
clear ind
end
This works but is extremely slow. How can I do this more efficiently?
Thanks
Jon

 Accepted Answer

I fiddled around with this further and addressed the loop, which was re-doing the "find" and settled on this...
C=A(:,1);
D=B(:,1);
idx=find(ismember(C,D));
A(:,2)=B(idx,2);
A(:,3)=B(idx,3);
A(:,4)=B(idx,4);
seems to work.

5 Comments

You can do it without the find() if you use
[~, idx] = ismember(C, D);
but beware that if any entry was not found then the corresponding idx will be 0. So safer is
[mask, idx] = ismember(C, D);
A(mask, 2:4) = B(idx(mask), 2:4);
Thanks this resolved my problem. I'm unclear about the role of 'mask'.
The first output of ismember() is an logical array the same size as the first parameter (C here), with the value set to true if the corresponding value in C was found in D, and false if it was not found. The second output of ismember() is a numeric array the same size as the first parameter (C here) with the value set to the index within D that the corresponding C entry was found, and 0 if it was not found.
With the first output (mask here) being a logical array that tells you where the second array is valid, then you can use logical indexing to say which parts of A and the index you want to work with. Your C is a vector the same length as the number of rows in A, so mask will be that same size, and now mask indicates whether to select that row or not; you do not want to select that row if the ID was not found in the B array (because you want to leave the entries as nan in that case.)
If I wanted to compare C and D to check, for example, if C is in between 2 values (in 2 different columns) of array D, how would I do that?
Two fixed columns? Or any two columns? If it is any two columns, then is D guaranteed to be non-decreasing along the rows? What is the desired output?
And to confirm, C and D are 2D and C and D have the same number of rows but not necessarily the same number of columns?
Or is C a column vector with the same number of entries that D has rows and the task is to find out which column the value is in relative to the content of that row of D?
Is there some pattern to the way D is arranged?

Sign in to comment.

More Answers (1)

ind = B(:,1)==A(i,1); % array of 5000000x1 logical
Try:
for i=1:length(A)
ind = find(B(:,1)==A(i,1),1,'first'); % one value
A(i,2:4) = B(ind,2:4);
% clear ind
end

1 Comment

Are those numbers you compare of integer format?

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!