如果使用“经典字符串”,则应定义二维。
可以使用netCDF以两种方式存储字符串,“经典字符串”和“字符串数组”(
https://www.unidata.ucar.edu/software/netcdf/netcdf-4/newdocs/netcdf-c/Strings.html
). "经典字符串“不需要NetCDF4.0+版本,下面的答案就是基于此。
%% Solution using classic string (without NETCDF-4)
ncfilename ='./AQS.nc';
uint_method=uint8('55-059-0019-88101-1');
method_ID = char(repmat(uint_method,10,1));
[a,b] = size(method_ID); %a=10, b=19
mode = bitor(netcdf.getConstant('CLOBBER'),netcdf.getConstant('64BIT_OFFSET'));
ncid = netcdf.create(ncfilename,mode);
globalVarId=netcdf.getConstant('GLOBAL');
netcdf.putAtt(ncid,globalVarId,'name','PM25_24hr_AQS');
%IDDimId = netcdf.defDim(ncid,'method_ID',a*b);
% IDDimId = netcdf.defDim(ncid,'method_ID',length(method_ID)); % ERROR: input elements does not match the variable size
% IDVarId = netcdf.defVar(ncid,'method_ID','char',IDDimId);
IDDim1 = netcdf.defDim(ncid,'charlen',b);
IDDim2 = netcdf.defDim(ncid,'methods',a);
IDVarId = netcdf.defVar(ncid,'method_ID','char',[IDDim1 IDDim2]);
netcdf.endDef(ncid);
netcdf.putVar(ncid,IDVarId,method_ID'); %transpose
netcdf.close(ncid);
你将得到:
$ ncdump AQS.nc
netcdf AQS {
dimensions:
charlen = 19 ;
methods = 10 ;
variables:
char method_ID(methods, charlen) ;
// global attributes:
:name = "PM25_24hr_AQS" ;
data:
method_ID =
"55-059-0019-88101-1",
"55-059-0019-88101-1",
"55-059-0019-88101-1",
"55-059-0019-88101-1",
"55-059-0019-88101-1",
"55-059-0019-88101-1",
"55-059-0019-88101-1",
"55-059-0019-88101-1",
"55-059-0019-88101-1",
"55-059-0019-88101-1" ;
}