If a value in one matrix matches that in another matrix, how do I assign the same index number?

I have a matrix with a list of latitude and longitude coordinates (64,800x3). Each latitude and longitude pair have their own index number.
Ex.
[Index Lat Lon;
10521 -45.5 50.5;
10522 -45.5 51.5;
10523 -45.5 52.5]
I have another matrix with a list of latitude and longitude numbers, but no index numbers. Also, this matrix is not the same size as the previous matrix. (250x2; It has Lat and Lon only, no index number yet.)
I want to write a script that will examine the pairs of latitude and longitude coordinates for each matrix. When there is a pair that matches between the matrices, it would assign the same index number to the second matrix from the first matrix.

 Accepted Answer

Sure you can. You can use the find function to find the index at which the 2nd and 3rd column match, and then copy the elements over.
Your code could look like this:
origMat = [10521 -45.5 50.5;
10522 -45.5 51.5;
10523 -45.5 52.5];
newMat = [0 -45.5 52.5;
0 -45.5 52.5;
0 -45.5 51.5;
0 -45.5 50.5];
% Loop through the new matrix
for ii = 1:size(newMat,1)
% Find the index location where 2nd and 3rd column match
idxLocation = origMat(:,2)==newMat(ii,2) & ...
origMat(:,3)==newMat(ii,3);
% If valid, set the index number (1st column) of the new matrix
if ~isempty(idxLocation)
newMat(ii,1) = origMat(idxLocation,1);
end
end
format short g
newMat
This gives me
newMat =
10523 -45.5 52.5
10523 -45.5 52.5
10522 -45.5 51.5
10521 -45.5 50.5

4 Comments

Actually find is not required: simply remove the find and use logical indexing, thus making your code simpler and faster. Beginners often use find when logical indexing would be a simpler solution. The MATLAB editor will also underline this command and recommend removing it.
@Sebastion Castro: you also might want to replace ~isempty with any.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!