MATLAB Answers

Importing NetCDF files: Script stops when a variable is missing from a file.

5 views (last 30 days)
Jaskabara
Jaskabara on 4 Apr 2020
Commented: Jaskabara on 9 Apr 2020
Found this script that I'm running when importing NetCDF files. It seems to work fine, but whenever a variabel is missing from a file the script will stop(or atleast i believe this to be the reason). It's seems that the salinty variabel is mostly related to the problem. Is there any way i can skip over these files?
ncvars = {'LATITUDE', 'LONGITUDE', 'PSAL', 'PRES'};
projectdir = 'C:\some\location';
dinfo = dir( fullfile(projectdir, '*.nc') );
num_files = length(dinfo);
filenames = fullfile( projectdir, {dinfo.name} );
lats = cell(num_files, 1);
lons = cell(num_files, 1);
salinity = cell(num_files, 1);
times = cell(num_files, 1);
for K = 1 : num_files
this_file = filenames{K};
lats{K} = ncread(this_file, ncvars{1});
lons{K} = ncread(this_file, ncvars{2});
salinity{K} = ncread(this_file, ncvars{3});
times{K} = ncread(this_file, ncvars{4});
end
Here's there error messages:
Error using internal.matlab.imagesci.nc/getGroupAndVarid (line 2096)
Could not find variable or group 'PSAL' in file.
Error in internal.matlab.imagesci.nc/read (line 593)
[gid, varid] = getGroupAndVarid(this, location);
Error in ncread (line 66)
vardata = ncObj.read(varName, varargin{:});
Error in Hydropraphy (line 14)
sal{K} = ncread(filen, variabler{3});
Any help would be greatly appreciated!

  0 Comments

Sign in to comment.

Accepted Answer

Sean de Wolski
Sean de Wolski on 4 Apr 2020
Use ncinfo to determine if the variable exists in the file before you to try to read it.

  3 Comments

Jaskabara
Jaskabara on 4 Apr 2020
Thanks for the answer! Can i put this in the script in some way? I have roughly 100 000 NetCDF files to import.
Sean de Wolski
Sean de Wolski on 6 Apr 2020
info = ncinfo(file(K))
names = {info.Variables.Name}
if ismember('your_name', names)
process_file_K
else
dont_process_file_K
end
Jaskabara
Jaskabara on 9 Apr 2020
Thanks! I got it to work with try, catch and end. But this seems more legit, will definetly try it out :)

Sign in to comment.

More Answers (0)

Sign in to answer this question.

Tags