netcdf.reDef 仅在 matlab 中可见的更改

netcdf.reDef changes seen only within matlab

当更改 netcdf 文件中的变量名称时,我仅在 Matlab 中看到更改。

特别是,我通过 nccreatencwrite:

使用 matlab 创建了一个 netcdf 文件
cd $PATH

ncfile = 'test.nc';

nccreate(ncfile,'Var1','Dimensions',{'time',20},'DeflateLevel',5);

ncwrite(ncfile,'Var1',rand(1,20),1);
ncwriteatt(ncfile,'Var1','Units','[m/s]');

通过Matlab内部检查(ncdisp)和通过shell(ncdump),结果变量名相同:

 ncdisp('test.nc') 
Source:
       $PATH/test.nc Format:
       netcdf4_classic Dimensions:
       time = 20 Variables:
Var1
       Size:       20x1
       Dimensions: time
       Datatype:   double
       Attributes:
                   Units = '[m/s]'
$ ncdump -h test.nc
netcdf test { dimensions:     time = 20 ; variables:  double Var1(time) ;
    Var1:Units = "[m/s]" ; }

但是,当我使用 Matlab 更改变量名称时:

cd $PATH

% Open netCDF file.
ncid = netcdf.open('test.nc','NC_WRITE');


% Put file in define mode.=
netcdf.reDef(ncid)


% Get name of first variable
[varname, xtype, varDimIDs, varAtts] = netcdf.inqVar(ncid,0);

varname


% Rename the variable, using a capital letter to start the name.
netcdf.renameVar(ncid,0,'velocity')


% Verify that the name of the variable changed.
[varname, xtype, varDimIDs, varAtts] = netcdf.inqVar(ncid,0);

varname
varname =

    'Var1'


varname =

    'velocity'

现在,只有 Matlab 可以看到更改:

ncdisp('test.nc')
Source:
       $PATH/test.nc Format:
       netcdf4_classic Dimensions:
       time = 20 Variables:
velocity
       Size:       20x1
       Dimensions: time
       Datatype:   double
       Attributes:
                   Units = '[m/s]'
$ ncdump -h test.nc 
netcdf test { dimensions:     time = 20 ; variables:  double Var1(time) ;
    Var1:Units = "[m/s]" ; }

事实上 ncdump 仍然看到一个名为 Var1 的变量。

有人知道这是什么原因吗?

您需要致电netcdf.syncnetcdf.close:

# ...
netcdf.renameVar(ncid,0,'velocity')
netcdf.sync(ncid)

# ...
netcdf.renameVar(ncid,0,'velocity')
netcdf.close(ncid)

netcdf.sync 之后您仍然可以使用 netcdf id ncid(为示例进行更多更改)。 netcdf.close.

不是这种情况

无需关闭 matlab 即可使这些更改对其他程序可见。

函数调用 netcdf.reDefnetcdf.endDef 只有在使用 NetCDF 3 文件时才需要 [1].

[1] https://www.unidata.ucar.edu/software/netcdf/workshops/2007/nc4features/Enddef.html