% % This is the name of the data file we will create. FILE_NAME='simple_xy.nc'; % % We are writing 2D data, a 6 x 12 grid. NDIMS=2; NX=6; NY=12; % % Create some pretend data. If this wasn't an example program, we % would have some real data to write, for example, model % output. data_out = [0:NX*NY-1]; % % Make it the same shape as the C example. % Due to the column-major ordering of MATLAB, this is a two-step % process. data_out = reshape(data_out,NY,NX); data_out = data_out'; % % And finally, change from double precision to 32-bit integer. data_out = int32(data_out); % % Always check the return code of every netCDF function call. In % this example program, any retval which is not equal to NC_NOERR % (0) will cause the program to print an error message and exit. % % Create the file. The NC_CLOBBER parameter tells netCDF to % overwrite this file, if it already exists [ncid, status] = mexnc ( 'CREATE', FILE_NAME, nc_clobber_mode ); if ( status ~= 0 ), error ( mexnc('STRERROR',status) ), end % % Define the dimensions. NetCDF will hand back an ID for each. [x_dimid, status] = mexnc ( 'DEF_DIM', ncid, 'x', NX ); if ( status ~= 0 ), error ( mexnc('STRERROR',status) ), end [y_dimid, status] = mexnc ( 'DEF_DIM', ncid, 'y', NY ); if ( status ~= 0 ), error ( mexnc('STRERROR',status) ), end % % The dimids array is used to pass the IDs of the dimensions of % the variable. dimids(1) = x_dimid; dimids(2) = y_dimid; % % Define the variable. The type of the variable in this case is % NC_INT (4-byte integer). [varid, status] = mexnc ( 'DEF_VAR', ncid, 'data', nc_int, 2, dimids ); if ( status ~= 0 ), error ( mexnc('STRERROR',status) ), end % % End define mode. This tells netCDF we are done defining % metadata. status = mexnc ( 'ENDDEF', ncid ); if ( status ~= 0 ), error ( mexnc('STRERROR',status) ), end % % Write the pretend data to the file. Although netCDF supports % reading and writing subsets of data, in this case we write all % the data in one operation. Don't forget to transpose the data! % % This could also have been done with nc_varput.m from SNCTOOLS. % It would have been called with % % >> nc_varput ( FILE_NAME, 'data', data_out ); status = mexnc ( 'PUT_VAR_INT', ncid, varid, data_out' ); if ( status ~= 0 ), error ( mexnc('STRERROR',status) ), end % % Close the file. This frees up any internal netCDF resources % associated with the file, and flushes any buffers. status = mexnc ( 'CLOSE', ncid ); if ( status ~= 0 ), error ( mexnc('STRERROR',status) ), end fprintf(1, '*** SUCCESS writing example file simple_xy.nc!\n');