Chapter 7.  Adding Variables

Table of Contents

Adding netCDF Variables

Adding netCDF Variables

So now we want to add the data variable. The m-file nc_addvar.m does the trick here, but it's a little different than the previous m-files that we've looked at in that it uses a structure to describe the variable. See the help documentation for more details, but the example below should illustrate the general idea.

>> varstruct.Name = 'myvar';
>> varstruct.Datatype = 'single';
>> varstruct.Dimension = { 'time', 'latitude', 'longitude' };
>> nc_addvar ( 'test.nc', varstruct )
>> nc_dump ( 'test.nc' )
netcdf test.nc {

dimensions:
        latitude = 20 ;
        longitude = 30 ;
        time = UNLIMITED ; (0 currently)


variables:
        float myvar(time,latitude,longitude), shape = [0 20 30]


}

    

Before writing to the data variable, it may have just occurred to us that maybe we should have data for the latitude, longitude, and time as well. Since these new variables would have the same names as the dimensions upon which they are defined, they are often referred to as coordinate variables.

>> lon_varstruct.Name = 'longitude';
>> lon_varstruct.Dimension = { 'longitude' };
>> lat_varstruct.Name = 'latitude';
>> lat_varstruct.Dimension = { 'latitude' };
>> time_varstruct.Name = 'time';
>> time_varstruct.Dimension = { 'time' };
>> nc_addvar ( 'test.nc', lon_varstruct )
>> nc_addvar ( 'test.nc', lat_varstruct )
>> nc_addvar ( 'test.nc', time_varstruct )
>> nc_dump ( 'test.nc' )
netcdf test.nc {

dimensions:
        latitude = 20 ;
        longitude = 30 ;
        time = UNLIMITED ; (0 currently)


variables:
        float myvar(time,latitude,longitude), shape = [0 20 30]
        double longitude(longitude), shape = [30]
        double latitude(latitude), shape = [20]
        double time(time), shape = [0]



}

    

Note that by not specifying a type, nc_addvar defaults to double precision.