Creating a NetCDF (.nc) file with variables that contain a different dimension

11 次查看(过去 30 天)
I am in the process of creating a code that converts various global grids taken along a time series (a few months) into a NetCDF (.nc) file (i.e. lon x lat x time). I have understood the general process of netcdf. Unfortunately I can't manage to save the grids with different sizes in different variables. If it is possible at all, how does this work?
Below is a code example that throws an error because it does not contain the same dimension:
grid1 = ones(180 , 360 , 5); % e.g. 180°x360° grid along 5 months
grid2 = ones(180 , 360 , 8); % e.g. 180°x360° grid along 8 months
grid3 = ones( 90 , 180 , 5); % e.g. 90°x180° grid along 5 months
nccreate("myfile.nc","grid1","Dimensions", {"lat",180,"lon",360,"t",5},"Format","classic");
ncwrite("myfile.nc","grid1",grid1);
nccreate("myfile.nc","grid2","Dimensions", {"lat",180,"lon",360,"t",8},"Format","classic");
Error using internal.matlab.imagesci.nc/createDimension (line 1174)
Cannot create dimension 't' of length 8. '/' already defines a fixed length dimension of the same name with length 5. Existing dimensions cannot be resized.

Error in internal.matlab.imagesci.nc/createDimensions (line 289)
this.createDimension(defgid, ...

Error in internal.matlab.imagesci.nc/createVariable (line 422)
this.createDimensions(groupName, dimensions);

Error in nccreate (line 182)
ncObj.createVariable(varName, varargin{:})
ncwrite("myfile.nc","grid2",grid2);
nccreate("myfile.nc","grid3","Dimensions", {"lat", 90,"lon",180,"t",5},"Format","classic");
ncwrite("myfile.nc","grid3",grid3);
Is it somehow possible not to define the dimension globally for all variables or is there any other possibility?

回答(1 个)

Ayush Modi
Ayush Modi 2024-5-14
Hi Simon,
You can define different dimension for each variable while creating the variables using "nccreate" function. Here is the modified code to achieve the same:
nccreate("myfile.nc", "grid1", "Dimensions", {"lat1", 180, "lon1", 360, "t1", 5}, "Format", "classic");
nccreate("myfile.nc", "grid2", "Dimensions", {"lat2", 180, "lon2", 360, "t2", 8}, "Format", "classic");
nccreate("myfile.nc", "grid3", "Dimensions", {"lat3", 90, "lon3", 180, "t3", 5}, "Format", "classic");
% Note, Dimension argument is added in each "nccreate" statement to define
% different dimensions for each variable.
Please refer to the following MathWorks documentation for more information on "Dimension" argument in "nccreate" function:

标签

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by