Reputation: 11
I have a function which generates yout_new(5000,1) at every iteration and I want to store this data to a netcdf file and append the new data generated at every iteration into this existing file . At the 2nd iteration the stored variable size should be yout_new(5000,2) . Here is my try which doesn't work. Is there is any nice way to do it ?
neq=5000;
filename='thrust.nc';
if ~exist(filename, 'file')
%% create file
ncid=netcdf.create(filename,'NC_WRITE');
%%define dimension
tdimID = netcdf.defDim(ncid,'t',...
netcdf.getConstant('NC_UNLIMITED'));
ydimID = netcdf.defDim(ncid,'y',neq);
%%define varibale
varid = netcdf.defVar(ncid,'yout','NC_DOUBLE',[ydimID tdimID]);
netcdf.endDef(ncid);
%%put variables from workspace ( i is the iteration)
netcdf.putVar(ncid,varid,[ 0 0 ],[ neq 0],yout_new);
%%close the file
netcdf.close(ncid);
else
%% open the existing file
ncid=netcdf.open(filename,'NC_WRITE');
%Inquire variables
[varname,xtype,dimids,natts] = netcdf.inqVar(ncid,0);
varid = netcdf.inqVarID(ncid,varname);
%Enquire current dimension length
[dimname, dimlen] = netcdf.inqDim(ncid,0);
% Append new data to existing variable.
netcdf.putVar(ncid,varid,dimlen,numel(yout_new),yout_new);
netcdf.close(ncid);
Upvotes: 1
Views: 693
Reputation: 1241
There are more easy functions in MATLAB, to deal with netCDF. You read about ncdisp, ncinfo,nccreate,ncread,ncwrite. Coming to the question, you said you have to write two columns, I will take number of columns as variable (infinity), every time you can append the columns. Check the below code:
N = 3 ; % number of columns
rows = 5000 ; % number of rows
ncfile = 'myfile.nc' ; % my ncfile name
nccreate(ncfile,'yout_new','Dimensions',{'row',rows,'col',Inf},'DeflateLevel',5) ; % creat nc file
% generate your data in loop and write to nc file
for i = 1:N
yout_new = rand(rows,1) ;
ncwrite(ncfile,'yout_new',yout_new,[1,i]) ;
end
Please not that, it is not mandatory to make number of columns as unlimited, you can fix it to your desired number instead of inf.
Upvotes: 1