how to find elements between two values

4 views (last 30 days)
Farshid Daryabor
Farshid Daryabor on 31 Jan 2020
Answered: Steven Lord on 21 Jul 2025
I want to check the netcdf files one by one based on the maximum and minimum of longitude and latitude in the corresponding files whether those are in between the maximum and minimum defined longitude and latitude, "latlim = [a, b]; lonlim = [c , d]". I wrote the following code, but it could not copy the corresponding files in the new file.
I really thanks in advance any help or suggestion.
filesout = {};
for i = 1 : length(files)
disp(['File number = ' , num2str(i)])
filename = files{i};
lat_min = str2double(ncreadatt(filename,'/','geospatial_lat_min'));
lat_max = str2double(ncreadatt(filename,'/','geospatial_lat_max'));
lon_min = str2double(ncreadatt(filename,'/','geospatial_lon_min'));
lon_max = str2double(ncreadatt(filename,'/','geospatial_lon_max'));
lon_argo = [lon_min, lon_max]; lat_argo = [lat_min, lat_max];
%
if ( (lon_argo(:) <= (min(lonlim))) & (lon_argo(:) > (max(lonlim))) & ...
(lat_argo(:) <= (min(latlim))) & lat_argo(:) > (max(latlim)) )
filesout = filename ;
fn = str2double(ncreadatt(filesout,'/','platform_code'));
disp(['Platform code = ' , num2str(fn)])
else
continue;
end
end

Answers (2)

Yash
Yash on 20 Jul 2025
There are a few errors in your code:
1) There is a logical error in the condition: (lon_argo(:) <= (min(lonlim))) & (lon_argo(:) > (max(lonlim))). This condition will always be false because no number can be both less than the minimum and greater than the maximum at the same time. You should modify the condition to check the values within the limits of latitude and longitude.
2) Append the file names to the "filesout" variable instead of overwriting it.
3) Use "copyfile" function to copy files instead of simply displaying their names.

Steven Lord
Steven Lord on 21 Jul 2025
If you're using release R2014b or later, use the isbetween function.
x = randi([-10 10], 5, 5)
x = 5×5
8 2 0 10 2 -7 3 0 4 8 -8 9 -3 -8 -1 10 1 7 7 9 7 -6 -4 3 6
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
xinrange = isbetween(x, -5, 5)
xinrange = 5×5 logical array
0 1 1 0 1 0 1 1 1 0 0 0 1 0 1 0 1 0 0 0 0 0 1 1 0
y = randi([-10 10], 5, 5)
y = 5×5
-1 3 -6 4 -8 0 5 -1 6 0 -6 -8 2 4 -5 3 8 6 -1 -8 6 -7 7 5 -1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
yinrange = isbetween(y, -5, 5)
yinrange = 5×5 logical array
1 1 0 1 0 1 1 1 0 1 0 0 1 1 1 1 0 0 1 0 0 0 0 1 1
inrange = xinrange & yinrange
inrange = 5×5 logical array
0 1 0 0 0 0 1 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 0
[reshape(x(inrange), [], 1), reshape(y(inrange), [], 1)]
ans = 6×2
2 3 3 5 0 -1 -3 2 3 5 -1 -5
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

Community Treasure Hunt

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

Start Hunting!