Fortran NetCDF - added new dimension need to fill

2019-09-04 05:45发布

问题:

I added a new dimension to an existing netCDF file in fortran using the following code -

retval = nf_open(cfn,NF_WRITE,ncid)
if (retval .ne. nf_noerr) call handle_err(retval)
retval = nf_redef(ncid)
if (retval .ne. nf_noerr) call handle_err(retval)
retval = nf_def_dim(ncid,"xyz",len,dimid_xyz)
if (retval .ne. nf_noerr) call handle_err(retval)        
retval = nf_enddef(ncid)

Now I want to be able to fill this dimension with values of zero. The cardinality of this set is equal to the cardinality of the variable in my case geopotential height. In addition I have three other dimensions - time(unlimited), latitude, longitude and level.

I looked up the netCDF API in fortran and I am not sure what is the API to call.When I use the following API

   retval = nf_put_var_real(ncid,dimid_xyz,xyzArray)
   if (retval .ne. nf_noerr) call handle_err(retval)

it ends up overwriting the geopotential height values with 0.0(which is the only variable in my netCDF file)

How do I go about doing this ?

回答1:

As I understand it a dimension is distinct from a variable, dimensions can't have values but variables can -- I think a fairly common practice may be to create the dimension and also create a variable with the same name. You can then give the variable whatever values you want.

Your code may look like

retval = nf_open(cfn,NF_WRITE,ncid)
if (retval .ne. nf_noerr) call handle_err(retval)
retval = nf_redef(ncid)
if (retval .ne. nf_noerr) call handle_err(retval)
retval = nf_def_dim(ncid,"xyz",len,dimid_xyz)
if (retval .ne. nf_noerr) call handle_err(retval) 

retval = nf_def_var(ncid,"xyz",netcdf_real,1,[dimid_xyz], varid_xyz)
if (retval .ne. nf_noerr) call handle_err(retval) 

retval = nf_enddef(ncid)

retval = nf_put_vara(ncid,varid_xyz,[1],[len],arrayOfZero)
if (retval .ne. nf_noerr) call handle_err(retval) 

Note I'd recommend against using a variable named len inside your fortran code -- this will clash with the intrinsic of the same name.