Main Content


Create netCDF variable


varid = netcdf.defVar(ncid,varname,xtype,dimids)


varid = netcdf.defVar(ncid,varname,xtype,dimids) creates a new variable in the data set identified by ncid.

  • varname is a character vector or string scalar that specifies the name of the variable.

  • xtype specifies the NetCDF data type of the variable, using one of these values.

    Value of xtypeMATLAB® Class
    NC_INT64 (NetCDF-4 files only)int64
    NC_UINT64 (NetCDF-4 files only)uint64
    NC_UINT (NetCDF-4 files only)uint32
    NC_USHORT (NetCDF-4 files only)uint16
    NC_UBYTE (NetCDF-4 files only)uint8
    NC_STRING (NetCDF-4 files only)string

    Alternatively, xtype can be the numeric equivalent returned by the netcdf.getConstant function. For user-defined NC_VLEN types, xtype can be the numeric value returned by the netcdf.defVlen function. NC_VLEN types correspond to cell arrays.

  • dimids specifies a list of dimension IDs.

  • netcdf.defVar returns varid, a numeric identifier for the new variable.

This function corresponds to the nc_def_var function in the NetCDF library C API. Because MATLAB uses FORTRAN-style ordering, the fastest-varying dimension comes first and the slowest comes last. Any unlimited dimension is therefore last in the list of dimension IDs. This ordering is the reverse of that found in the C API. To use this function, you should be familiar with the NetCDF programming paradigm.


collapse all

Create a new NetCDF file, define a dimension in the file, and then define a variable on that dimension. In NetCDF files, you must create a dimension before you can create a variable. To run this example, you must have write permission in your current folder.

Create a new NetCDF file named

ncid = netcdf.create('','NC_NOCLOBBER');

Define a dimension in the new file.

dimid = netcdf.defDim(ncid,'x',50);

Define a variable in the new file using netcdf.defVar.

varid = netcdf.defVar(ncid,'myvar','NC_DOUBLE',dimid)
varid = 0

netcdf.defVar returns a numeric identifier for the new variable.

Close the file.



  • MATLAB interprets multidimensional data as column-major, but the netCDF C API interprets multidimensional data as row-major. Multidimensional data in the netCDF C API shows dimensions in the reverse of the order shown by MATLAB and consequently appears transposed.

Version History

expand all