How to write fill values instead of NaN values in netCDF file

19 views (last 30 days)
I'm using Matlab to create a netCDF file with NaN values in its variables.
Ideally I would like to substitute the NaNs of the Matlab variables by the default netCDF fill values when writing the netCDF. But I can't do it.
I understood from the Matlab doc that that's automatically done,
But it's not (I don't define any attribute). I guess the problem is very silly... but I can't find it.
This is basically what I'm doing:
A=1:20;
A(A<10)=NaN;
nccreate('file.nc','A','Format','netcdf4','Datatype','single','Dimensions',{'length' 20});
ncwrite('file.nc','A',A)
Checking file.nc with my viewer I find NaN values instead of the value of NC_FILL_SHORT (-32767) defined in the netCDF library. But I don't know why.
If I select 'Datatype','int16' (to be consistent with my example) the I get 0 values instead of NaN...
Any ideas?
Thanks!

Answers (2)

KSSV
KSSV on 30 Aug 2017
Either you need to fill the NaN's before writing into nc file or read the variable and fill NaN's while using it. There are ways to fill NaN's..you can check for interp1 and interp2 to fill the NaN's via interpolation. Or you can use fillmissing if you are using MATLAB version 2016b or more.

Zhao-Yang CHAI
Zhao-Yang CHAI on 21 Jun 2018
You can define fillvalue by yourself.
A=1:20;
A(A<10)=NaN;
fillvalue = 1.0e+36;
nccreate('file.nc','A','Format','netcdf4','Datatype','single',...
'Dimensions',{'length' 20},'FillValue',fillvalue);
ncwrite('file.nc','A',A)
It's better to make sure the datatypes of variable A and 'Datatype' in function nccreate are the same, or you will have something wrong with fillvalue. For example, the following codes will be wrong.
A=1:20;
A=single(A);%convert to single
A(A<10)=NaN;
fillvalue = 1.0e+36;
nccreate('file.nc','A','Format','netcdf4','Datatype','double',...
'Dimensions',{'length' 20},'FillValue',fillvalue);%datatype of A is not 'double'
ncwrite('file.nc','A',A)
However, the following codes will be right.
A=1:20;
A=double(A);%convert to double
A(A<10)=NaN;
fillvalue = 1.0e+36;
nccreate('file.nc','A','Format','netcdf4','Datatype','single',...
'Dimensions',{'length' 20},'FillValue',fillvalue);%datatype of A is not 'single'
ncwrite('file.nc','A',A)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!