Next: , Previous: Variable Types, Up: Variables


4.3 Create a Variable: nc_def_var

The function nc_def_var adds a new variable to an open netCDF dataset in define mode. It returns (as an argument) a variable ID, given the netCDF ID, the variable name, the variable type, the number of dimensions, and a list of the dimension IDs.

Usage

     int nc_def_var (int ncid, const char *name, nc_type xtype,
                     int ndims, const int dimids[], int *varidp);
ncid
NetCDF ID, from a previous call to nc_open or nc_create.
name
Variable name. Must begin with an alphabetic character, followed by zero or more alphanumeric characters including the underscore ('_'). Case is significant.
xtype
One of the set of predefined netCDF external data types. The type of this parameter, nc_type, is defined in the netCDF header file. The valid netCDF external data types are NC_BYTE, NC_CHAR, NC_SHORT, NC_INT, NC_FLOAT, and NC_DOUBLE.
ndims
Number of dimensions for the variable. For example, 2 specifies a matrix, 1 specifies a vector, and 0 means the variable is a scalar with no dimensions. Must not be negative or greater than the predefined constant NC_MAX_VAR_DIMS.
dimids
Vector of ndims dimension IDs corresponding to the variable dimensions. If the ID of the unlimited dimension is included, it must be first. This argument is ignored if ndims is 0.
varidp
Pointer to location for the returned variable ID.

Errors

nc_def_var returns the value NC_NOERR if no errors occurred. Otherwise, the returned status indicates an error. Possible causes of errors include:

Example

Here is an example using nc_def_var to create a variable named rh of type double with three dimensions, time, lat, and lon in a new netCDF dataset named foo.nc:

     #include <netcdf.h>
        ...
     int  status;                       /* error status */
     int  ncid;                         /* netCDF ID */
     int  lat_dim, lon_dim, time_dim;   /* dimension IDs */
     int  rh_id;                        /* variable ID */
     int  rh_dimids[3];                 /* variable shape */
        ...
     status = nc_create("foo.nc", NC_NOCLOBBER, &ncid);
     if (status != NC_NOERR) handle_error(status);
        ...
                                        /* define dimensions */
     status = nc_def_dim(ncid, "lat", 5L, &lat_dim);
     if (status != NC_NOERR) handle_error(status);
     status = nc_def_dim(ncid, "lon", 10L, &lon_dim);
     if (status != NC_NOERR) handle_error(status);
     status = nc_def_dim(ncid, "time", NC_UNLIMITED, &time_dim);
     if (status != NC_NOERR) handle_error(status);
        ...
                                        /* define variable */
     rh_dimids[0] = time_dim;
     rh_dimids[1] = lat_dim;
     rh_dimids[2] = lon_dim;
     status = nc_def_var (ncid, "rh", NC_DOUBLE, 3, rh_dimids, &rh_id);
     if (status != NC_NOERR) handle_error(status);