1 function [p,dims]=nc2struct(filename,varnames,gattnames,timestep,p)
2 % p=nc2struct(filename,varnames,gattnames,timestep,p)
3 % read from netcdf file to structure
7 % filename string, name of file to read
8 % varnames cell array of strings, names of variable to read
9 % gattnames cell array of strings, names of global attributes to read
10 % times (optional) matrix of indices in the last dimension to extract (timestep in WRF)
11 % p (optional) the structure to add to
13 % p matlab structure with the specifed variables and attributes as fields
14 % with names in lowercase. The types are kept and the dimensions
18 % p=nc2struct('wrfinput_d01',{'U','V'},{'DX','DY'})
19 % will read variables U,V into p.u, p.v and global attributes DX DY into
20 % p.dx p.dy, respectively
22 if ~exist('timestep','var'),
25 fprintf('nc2struct: reading all timesteps\n')
26 elseif isscalar(timestep) & isnumeric(timestep),
27 fprintf('nc2struct: reading timestep %i only\n',timestep)
28 t=timestep-1; % netcdf dimensions start from 0
30 error('timestep must be numeric scalar')
34 fprintf('nc2struct: reading from file %s\n',filename)
37 ncid = netcdf.open(filename,'NC_NOWRITE');
39 disp(['cannot open NetCDF file ',filename])
44 p.filename{1}=filename;
49 for i=1:length({varnames{:}}),
52 v=ncvar(filename,varname,[]);
54 warning(['variable ',varname,' does not exist in file ',filename])
57 field = strrep(lower(varname),'-','__');
59 ndims=length(v.dimlength);
62 if t >= 0, % read only one dimestep
63 if(v.dimids(ndims)~=0),
64 warning('id of the last dimension is not 0, is it timestep?')
69 v = ncvar(filename,varname,start, count);
70 p.(field)=double(v.var_value);
71 dims.(field)=v.dimlength;
79 for i=1:length({gattnames{:}}),
80 gattname=gattnames{i};
82 val=ncgetgatt(filename,gattname);
84 warning(['global attribute ',gattname,' does not exist in file ',filename])
87 p.(lower(gattname))=double(val);