Append data to 2-D array Netcdf format Matlab

时间:2017-06-12 17:06:52

标签: matlab netcdf

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);

1 个答案:

答案 0 :(得分:1)

MATLAB中有更简单的函数来处理netCDF。您了解 ncdisp ncinfo nccreate ncread ncwrite 。来到这个问题,你说你必须写两列,每次你可以追加列时我会将列数作为变量(无穷大)。检查以下代码:

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

请注意,并非强制要求将列数设置为无限制,您可以将其修改为所需的数字而不是 inf