'Find' command to find index of lat and long from an array
6 views (last 30 days)
I am trying to extract the index of latitude and longitude from an array using 'find' command. My lat/long array contains latitude and longitude for the whole globe. I am using a code where I require only couple of lat/longs to be matched from the global array but its showing me that there is no match. Below is the code if anybody can help:
LG=[52.25 53.25 54.25]; % desired longitude values
LT=[21.65 22.65 23.65]; % desired latitude values
% Step 2 : Display all varaibles in nc file using command: ncdisplay
% Step 3 : Read varaibles from nc file by command : ncread
%Variable=input('write your main variable=');
% Step 4 : Find index of longitude and latitude in the dimension of array
% using command : find
LGG=find(long == LG(i));
LTT=find(lat == LT(i));
Here I get 'NAN' display. Can somebody tell where is the error? I have attached the nc file as well.
KSSV on 30 May 2022
You should not use find. As lat, lon are floating point numbers using == will not work. You need to define a small tolerance value and check the difference.
tol = 10^-3 ;
if LGG || LTT % check this logic accordingly
You need not to use a loop. You can do this in one line.
Also have a look on knnsearch
More Answers (1)
Walter Roberson on 30 May 2022
Your code assumes that exactly those latitudes and longitudes appear in the file. You are testing for bit-for-bit identical representations of numbers that binary floating point inherently cannot store the exact representation of. Binary floating point cannot represent 1/10 or 1/100 exactly so for example,
That would have to be the exact value stored in the file, not just something that rounded to the 21.65 to the nearest 1/100.
I suggest that you use interp2() instead of looking for exact equality.