write .nc in matlab

To write .nc (netCDF) files in MATLAB, follow these steps:

  1. Open or create a netCDF file for writing using the netcdf.create function. Use this function to specify the name of the file and the type of netCDF file you want to create (classic or 64-bit offset).
main.m
ncid = netcdf.create('example.nc','NC_CLOBBER');
49 chars
2 lines
  1. Use the netcdf.defDim function to define dimensions for the variables you want to write. You can define unlimited dimensions or fixed dimensions depending on your data requirements.
main.m
dimid1 = netcdf.defDim(ncid,'time', Inf);
dimid2 = netcdf.defDim(ncid,'lat',100);
dimid3 = netcdf.defDim(ncid,'lon',100);
122 chars
4 lines
  1. Use the netcdf.defVar function to define the variables you want to write into the file. This includes the variable name, datatype, dimensions, and any attributes associated with the variable.
main.m
varid1 = netcdf.defVar(ncid,'temperature','float',[dimid1 dimid2 dimid3]);
netcdf.putAtt(ncid,varid1,'long_name','surface temperature');
137 chars
3 lines
  1. Use the netcdf.endDef function to end the definition mode and switch to data writing mode.
main.m
netcdf.endDef(ncid);
21 chars
2 lines
  1. Write the data to the file using the netcdf.putVar function. This function takes the variable ID, a starting index for each dimension, and the data you want to write.
main.m
data = rand(10,100,100);
netcdf.putVar(ncid,varid1,[0 0 0],[10 100 100],data);
79 chars
3 lines
  1. Close the file using the netcdf.close function.
main.m
netcdf.close(ncid);
20 chars
2 lines

This will create a new netCDF file called example.nc, with a variable called temperature that has dimensions time, lat, and lon, and associated data and attributes.

gistlibby LogSnag