%% Loading data from a NetCDF file

%% Open file
%
% First, open the file.
%
ncid = netcdf.open('4900093_trajectory.nc', 'NC_NOWRITE');
%%
% Here 'NC_NOWRITE' means that the file can only be read, but not written
% to. Alternatively we could specify 'NC_WRITE', which means that the file 
% can be read and written to.

%% Inquire about file content
% Second, get an overview about the file content ('inquire' about the 
% content).
%
[ndims,nvars,ngatts,unlimdimid] = netcdf.inq(ncid)
%%
% The function returns the number of dimensions, variables, global 
% attributes and id of unlimited dimension if one exists.
%
%
% Next, find out dimension names and lengths
% (Note that ids in NetCDF file start counting at 0, but matlab arrays
% always start at 1).
%
for i=1:ndims
  [dimname{i}, dimlen(i)] = netcdf.inqDim(ncid,i-1);
end

dimname

%%
% Find out about variable names, data type, dimensions ids, and number of 
% attributes associated with each variable.
%
for i=1:nvars
  [varname{i},xtype(i),dimids{i},natts(i)] = netcdf.inqVar(ncid,i-1);
end

varname

%%
% Note the variables JULD, LATITUDE, LONGITUDE, PRES, DOXY, PSAL, TEMP
% which we are interested in.
%
% Find out more about these variables, e.g. attributes of latitude 
% (variable 20) 

var = 20;
for i=1:natts(var)
  attname{i} = netcdf.inqAttName(ncid,var-1,i-1);
  attrvalue{i} = netcdf.getAtt(ncid,var-1,attname{i});
end

attname{1:2}
attrvalue{1:2}

%% Retrieve data from the file
%
% Now, we want to retrieve time, latitude and longitude, pressure, dissolved
% oxygen, salinity and temperature.
%
% Start with time by identifying the corresponding id.

timeid = 17;
%%
% Double-check that timeid corresponds to JULD:

varname{timeid+1}
%% 
% Load time:
time = netcdf.getVar(ncid,timeid);

%%
% Now, instead of loading every variable separately, load them more
% efficiently in a loop.
%
% First identify variable ids and define names we want to use: 
varids = [19 20 24 29 34 39];
myvarnames = {'lat' 'lon' 'pres' 'oxy' 'sal' 'temp'};
%%
% Double-check ids:
varname{varids+1}
%%
% Now load all variables in a loop:
for i=1:length(varids)
  data = netcdf.getVar(ncid,varids(i));
  eval([myvarnames{i} '=data;'])
end

%% Closing the file
%
% When done don't forget to close the netcdf file.
netcdf.close(ncid)








