MODIS .nc data can be tricky unlike other climate data format
chlFileDirectory = "Your folder";
chlFilename = dir(fullfile(chlFileDirectory, '*_chl.nc'));
nChlFiles = length(chlFilename); % Rename the variable
outputFolder = "Folder for the output files";
for i = 1:nChlFiles
chl_nc_filename = chlFilename(i).name;
chl_nc_file_path = fullfile(chlFileDirectory, chl_nc_filename);
min_lat = 27;
max_lat = 31;
min_lon = -95;
max_lon = -88;
% Read chlorophyll data from the current file
chl_image = ncread(chl_nc_file_path, 'chl_image');
latitude = ncread(chl_nc_file_path, 'latitude');
longitude = ncread(chl_nc_file_path, 'longitude');
in_box_idx_lat = find(latitude >= min_lat & latitude <= max_lat) ;
in_box_idx_lon =find(longitude >= min_lon & longitude <= max_lon);
% Clip the data to the bounding box
lat_clip = latitude(in_box_idx_lat);
lon_clip = longitude(in_box_idx_lon);
latDiff = abs(latitude(1,1) - latitude(1,2));
lonDiff = abs(longitude(1,1) - longitude(1,2));
latLim = max(lat_clip):-latDiff:min(lat_clip); % decsending order
lonLim = min(lon_clip):lonDiff:max(lon_clip);% ascending order
% Create a meshgrid for desired output points
[lon_mesh, lat_mesh] = meshgrid(lonLim, latLim);
chl_image_clipped = griddata(double(latitude), double(longitude), double(chl_image),...
double(lat_mesh), double(lon_mesh));
dim_clip = size(chl_image_clipped);
nrows = dim_clip(1);
ncols = dim_clip(2);
% Create the output chlorophyll file name
[filepath, name, ext] = fileparts(filename(i).name);
chl_nc_filename = strcat(name, '_clipped_chl.nc');
chl_nc_file_path = fullfile(outputFolder, chl_nc_filename);
nccreate(chl_nc_file_path, 'chl_image', 'Dimensions', {'row', nrows, 'col', ncols});
nccreate(chl_nc_file_path, 'longitude_clip', 'Dimensions', {'row', nrows, 'col',ncols });
nccreate(chl_nc_file_path, 'latitude_clip', 'Dimensions', {'row', nrows, 'col', ncols});
ncwrite(chl_nc_file_path, 'longitude_clip', lon_mesh);
ncwrite(chl_nc_file_path, 'latitude_clip', lat_mesh);
ncwrite(chl_nc_file_path, 'chl_image', chl_image_clipped);
end