Home > atmlab > files > loadncattr.m

loadncattr

PURPOSE ^

% loadncattr

SYNOPSIS ^

function attributes = loadncattr( ncfile , varargin)

DESCRIPTION ^

% loadncattr

 PURPOSE
         Load the attributes for all variables in a netcdf file, or just a
         subset of them

 IN
       ncfile          is either a string filename 
                       OR
                       an id of an already open netcdf file

       variables       {'str','str2'} variables to read. if none are given, read all

 OUT
       attributes       struct

 Salomon Eliasson
 $Id: loadncattr.m 8189 2013-02-11 14:06:53Z olemke $

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

DOWNLOAD ^

loadncattr.m

SOURCE CODE ^

0001 function attributes = loadncattr( ncfile , varargin)
0002 %% loadncattr
0003 %
0004 % PURPOSE
0005 %         Load the attributes for all variables in a netcdf file, or just a
0006 %         subset of them
0007 %
0008 % IN
0009 %       ncfile          is either a string filename
0010 %                       OR
0011 %                       an id of an already open netcdf file
0012 %
0013 %       variables       {'str','str2'} variables to read. if none are given, read all
0014 %
0015 % OUT
0016 %       attributes       struct
0017 %
0018 % Salomon Eliasson
0019 % $Id: loadncattr.m 8189 2013-02-11 14:06:53Z olemke $
0020 
0021 errId = ['atmlab:' mfilename];
0022 
0023 if ischar(ncfile)
0024     % UNCOMPRESS if needed
0025     if strcmp(ncfile(end-2:end),'.gz')
0026         tmpdir = create_tmpfolder;
0027         c= onCleanup(@() rmdir(tmpdir,'s'));
0028         ncfile = uncompress(ncfile,tmpdir);
0029         if isempty(ncfile), error(errId,'Uncompressing failed'); end
0030     end
0031     
0032     ncid = netcdf.open (ncfile, 'NOWRITE');
0033     cleanupObject = onCleanup(@() netcdf.close (ncid));
0034     
0035 else
0036     ncid = ncfile;
0037 end
0038 
0039 [~,nvars] = netcdf.inq(ncid);
0040 
0041 [inVars] = optargs(varargin,{''});
0042 isstr=~iscell(inVars); % if only one varname is given
0043 if isstr, inVars={inVars}; end
0044 
0045 attributes = struct();
0046 for i = 0:nvars-1
0047     [varname, ~, ~, natts] = netcdf.inqVar (ncid, i);
0048     svarname = genvarname(varname);
0049     if ~isempty(varargin) && ~any(ismember(inVars,svarname)) % skip if I want specific vars
0050         continue
0051     end
0052     for j = 0:natts-1
0053         attname = netcdf.inqAttName (ncid, i, j);
0054         if ~isempty(varargin) && isstr 
0055             attributes.(genvarname(attname)) = ...
0056                 netcdf.getAtt (ncid, i, attname);
0057         else
0058             attributes.(svarname).(genvarname(attname)) = ...
0059                 netcdf.getAtt (ncid, i, attname);
0060             
0061         end
0062     end
0063 end
0064 
0065 end

Generated on Mon 15-Sep-2014 13:31:28 by m2html © 2005