Writing a variable to a netcdf

8 visualizaciones (últimos 30 días)
Daneisha Blair
Daneisha Blair el 27 de Ag. de 2021
Respondida: Vaibhav el 19 de Abr. de 2024
Hi,
I'm having an issue with adding a variable to a netcdf. The error message I've recieved is:
Error using netcdflib
The number of input elements does not match the variable size.
Error in netcdf.putVar (line 88)
netcdflib(funcstr,ncid,varid,varargin{:});
Error in netcdf.putVar(ncid,varid,div2);
Here's my script I'm using:
% Create a netCDF file.
ncid = netcdf.create('foo.nc','NC_WRITE');
% Define a dimension in the file.
dimid = netcdf.defDim(ncid,'my_dim',length(div2));
% define a new variable in the file
varid=netcdf.defVar(ncid,'divergence','NC_FLOAT',dimid);
% Leave define mode and enter data mode to write data.
netcdf.endDef(ncid);
% Write data to variable.
netcdf.putVar(ncid,varid,div2);
% Re-enter define mode.
netcdf.reDef(ncid);
%create an attribute associated with the variable
netcdf.putAtt(ncid, varid, 'long_name', 'Ocean surface wind divergence');
netcdf.putAtt(ncid, varid, 'units', '1/s');
Side note: div2 is the name of the variable I would like to add to the netcdf. Its length is 205 and has a size of 205 x 141.
Any help is appreciated.

Respuestas (1)

Vaibhav
Vaibhav el 19 de Abr. de 2024
Hi Daneisha
The error message indicates that the size of the data being written (div2) does not match the expected size based on the dimensions defined in the netCDF file. In the script, a single dimension (my_dim) has been specified for the variable "divergence" but a 2D array (div2 with a size of 205x141) is being written to a variable that is defined with only one dimension. To resolve this issue, the variable needs to be defined with two dimensions to match the shape of the div2 array.
Here is how the script can be adjusted:
% Create a netCDF file.
ncid = netcdf.create('foo.nc','NC_WRITE');
% Define dimensions in the file.
dimid1 = netcdf.defDim(ncid,'dim1',205); % Corresponds to the first dimension of div2
dimid2 = netcdf.defDim(ncid,'dim2',141); % Corresponds to the second dimension of div2
% Define a new variable in the file with two dimensions
varid = netcdf.defVar(ncid,'divergence','NC_FLOAT',[dimid1 dimid2]);
% Leave define mode and enter data mode to write data.
netcdf.endDef(ncid);
% Write data to variable.
netcdf.putVar(ncid,varid,div2);
% Re-enter define mode if you want to add attributes or define more variables
netcdf.reDef(ncid);
% Create an attribute associated with the variable
netcdf.putAtt(ncid, varid, 'long_name', 'Ocean surface wind divergence');
netcdf.putAtt(ncid, varid, 'units', '1/s');
% Don't forget to close the file when you're done
netcdf.close(ncid);
Hope this helps!

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by