How to create a new NETCDF file with an existing variable?

21 次查看(过去 30 天)
I have a script in which I produced a 3D variable named "mask3", now I have to create a completely new NETCDF file in which I have to put this variable mask3. How could I do it? Thank you so much

回答(1 个)

Gayatri
Gayatri 2024-2-29
Hi Fabrizio,
To create a new NETCDF file and write 3D variable to it, you can use MATLAB's built-in functions for working with NETCDF files.
Here's an example MATLAB script that demonstrates this process:
% Example 3D variable 'mask3' with random data
mask3 = rand(50, 75, 20); % Replace with your actual data
[X, Y, Z] = size(mask3);
% Define the path and name of the new NETCDF file
filename = 'my_new_netcdf_file.nc';
% Create a new NETCDF file
ncid = netcdf.create(filename, 'NETCDF4');
% Define the dimensions in the NETCDF file
dimidX = netcdf.defDim(ncid, 'X', X);
dimidY = netcdf.defDim(ncid, 'Y', Y);
dimidZ = netcdf.defDim(ncid, 'Z', Z);
% Define the variable in the NETCDF file. Here we assume the data type of mask3 is double
varid = netcdf.defVar(ncid, 'mask3', 'double', [dimidX, dimidY, dimidZ]);
% Leave define mode
netcdf.endDef(ncid);
% Write the data to the variable
netcdf.putVar(ncid, varid, mask3);
netcdf.close(ncid); % Close the NETCDF file
This script will create a NETCDF file named "my_new_netcdf_file.nc" in your current MATLAB directory containing the variable "mask3" with the random data.
If you want to verify the contents of the created file, you can use MATLAB's "ncdisp" function:
ncdisp(filename); %This will display the information about the NETCDF file, including dimensions, variables, and attributes.
Please refer the below documentation for "ncdisp" function: https://in.mathworks.com/help/matlab/ref/ncdisp.html
I hope it helps!

Community Treasure Hunt

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

Start Hunting!

Translated by