Exporting to NetCDF Files

Overview

Network Common Data Form (NetCDF) is a set of software libraries and machine-independent data formats that support the creation, access, and sharing of array-oriented scientific data. NetCDF is used by a wide range of engineering and scientific fields that want a standard way to store data so that it can be shared. For more information, read the NetCDF documentation available at the Unidata Web site.

MATLAB® provides two methods to export data from the workspace into a NetCDF file:

  • High-level functions that make it easy to export data

  • Low-level functions that provide access to routines in the NetCDF C library

    Note   For information about exporting to Common Data Format (CDF) files, which have a completely separate and incompatible format, see Exporting to NetCDF Files.

Using the NetCDF High-Level Functions to Export Data

MATLAB includes several functions that you can use to export data from the file into the MATLAB workspace.

  • nccreate — Create a variable in a NetCDF file. If the file does not exist, nccreate creates it.

  • ncwrite — Write data to a NetCDF file

  • ncwriteatt — Write data to an attribute associated with a variable in a NetCDF file or with the file itself (global attribute)

  • ncwriteschema — Add a NetCDF schema to a NetCDF file, or create a new file using the schema as a template.

For details about how to use these functions, see their reference pages. These pages include examples. For information about importing (reading) data from a NetCDF file, see Using the MATLAB High-Level NetCDF Functions to Import Data. The following examples illustrate how to use these functions to perform several common scenarios:

Creating a New NetCDF File from an Existing File or Template

This example describes how to create a new file based on an existing file (or template).

  1. Read the variable, dimension, and group definitions from the file using ncinfo. This information defines the file's schema.

    finfo = ncinfo('example.nc');
  2. Create a new NetCDF file that uses this schema, using ncwriteschema.

    ncwriteschema('mynewfile.nc',finfo);
  3. View the existing file and the new file, using ncdisp. You can see how the new file contains the same set of dimensions, variables, and groups as the existing file.

      Note:   A schema defines the structure of the file but does not contain any of the data that was in the original file.

    ncdisp('example.nc')
    ncdisp('mynewfile.nc')

Converting Between NetCDF File Formats

This example shows how to convert an existing file from one format to another.

    Note:   When you convert a file's format using ncwriteschema, you might get a warning message, if the original file format includes fields that are not supported by the new format. For example, the netcdf4 format supports fill values but the NetCDF classic format does not. In these cases, ncwriteschema still creates the file, but leaves out the field that is undefined in the new format.

  1. Create a new file containing one variable, using the nccreate function.

    nccreate('ex1.nc','myvar');
  2. Determine the format of the new file, using ncinfo.

    finfo = ncinfo('ex1.nc');
    file_fmt = finfo.Format
    
    file_fmt =
    
    netcdf4_classic
  3. Change the value of the Format field in the finfo structure to another supported NetCDF format. You use the finfo structure to specify the new format.

    finfo.Format = 'netcdf4';
  4. Create a new version of the file that uses the new format, using the ncwriteschema function.

    finfo = ncwriteschema('newfile.nc',finfo);
    finfo = ncinfo('newfile.nc');
    new_fmt = finfo.Format
    
    file_fmt =
    
    netcdf4

      Note:   The new file contains the variable and dimension definitions of the original file, but does not contain the data. You must write the data to the file.

Merging Two NetCDF Files

This example shows how to merge two NetCDF files.

    Note:   The combined file contains the variable and dimension definitions of the files that are combined, but does not contain the data in these original files.

  1. Create a file, define a variable in the file, and write data to the variable.

    nccreate('ex1.nc','myvar');
    ncwrite('ex1.nc','myvar',55)
    ncdisp('ex1.nc')
    
  2. Create a second file, with another variable, and write data to it.

    nccreate('ex2.nc','myvar2');
    ncwrite('ex2.nc','myvar2',99)
    ncdisp('ex2.nc')
    
  3. Get the schema of each of the newly created files, using ncinfo.

    finfo1 = ncinfo('ex1.nc')
    
    finfo1 = 
    
          Filename: 'H:\file1.nc'
              Name: '/'
        Dimensions: []
         Variables: [1x1 struct]
        Attributes: []
            Groups: []
            Format: 'netcdf4_classic'
    
    finfo2 = ncinfo('file2.nc')
    
    finfo2 = 
    
          Filename: 'H:\file2.nc'
              Name: '/'
        Dimensions: []
         Variables: [1x1 struct]
        Attributes: []
            Groups: []
            Format: 'netcdf4_classic'
  4. Create a new NetCDF file that uses the schema of the first example file, using ncwriteschema.

    ncwriteschema('combined_file.nc',finfo1);
    
    ncdisp('combined_file.nc')
    Source:
               H:\combined_file.nc
    Format:
               netcdf4_classic
    Variables:
        myvar1
               Size:       1x1
               Dimensions: 
               Datatype:   double
               Attributes:
                           _FillValue = 9.97e+036
    
  5. Add the schema from the second example file to the newly created file, using ncwriteschema. When you view the contents, notice how the file now contains the variable defined in the first example file and the variable defined in the second file.

    ncwriteschema('combined_file.nc',finfo2);
    
    ncdisp('combined_file.nc')
    Source:
               H:\combined_file.nc
    Format:
               netcdf4_classic
    Variables:
        myvar1
               Size:       1x1
               Dimensions: 
               Datatype:   double
               Attributes:
                           _FillValue = 9.97e+036
        myvar2
               Size:       1x1
               Dimensions: 
               Datatype:   double
               Attributes:
                           _FillValue = 9.97e+036

Using the NetCDF Low-Level Functions to Export Data

MATLAB provides access to the routines in the NetCDF C library that you can use to read data from NetCDF files and write data to NetCDF files. MATLAB provides this access through a set of MATLAB functions that correspond to the functions in the NetCDF C library. MATLAB groups the functions into a package, called netcdf. To call one of the functions in the package, you must specify the package name. For a complete list of all the functions, see netcdf.

This section does not describe all features of the NetCDF library or explain basic NetCDF programming concepts. To use the MATLAB NetCDF functions effectively, you should be familiar with the information about NetCDF contained in the NetCDF C Interface Guide.

Exporting (Writing) Data to a NetCDF File

To store data in a NetCDF file, you can use the MATLAB NetCDF functions to create a file, define dimensions in the file, create a variable in the file, and write data to the variable. Note that you must define dimensions in the file before you can create variables. To run the following example, you must have write permission in your current folder.

  1. Create a variable in the MATLAB workspace. This example creates a 50-element vector of numeric values named my_data. The vector is of class double.

    my_data = linspace(0,49,50);
    
  2. Create a NetCDF file (or open an existing file). The example uses the netcdf.create function to create a new file, named my_file.nc. The NOCLOBBER parameter is a NetCDF file access constant that indicates that you do not want to overwrite an existing file with the same name. See netcdf.create for more information about these file access constants.

    ncid = netcdf.create('my_file.nc','NOCLOBBER');
    

    When you create a NetCDF file, the file opens in define mode. You must be in define mode to define dimensions and variables.

  3. Define a dimension in the file, using the netcdf.defDim function. You must define dimensions in the file before you can define variables and write data to the file. When you define a dimension, you give it a name and a length. To create an unlimited dimension, i.e., a dimension that can grow, specify the constant NC_UNLIMITED in place of the dimension length.

    dimid = netcdf.defDim(ncid,'my_dim',50);
    
  4. Define a variable on the dimension, using the netcdf.defVar function. When you define a variable, you give it a name, data type, and a dimension ID.

    varid = netcdf.defVar(ncid,'my_var','NC_BYTE',dimid);
    

    You must use one of the NetCDF constants to specify the data type, listed in the following table.

    MATLAB ClassNetCDF Data Type
    int8NC_BYTE[a]
    uint8NC_BYTE[b]
    charNC_CHAR
    int16NC_SHORT
    uint16No equivalent
    int32NC_INT
    uint32No equivalent
    int64No equivalent
    uint64No equivalent
    singleNC_FLOAT
    doubleNC_DOUBLE

    [a] NetCDF interprets byte data as either signed or unsigned.

    [b] NetCDF interprets byte data as either signed or unsigned.

  5. Take the NetCDF file out of define mode. To write data to a file, you must be in data mode.

    netcdf.endDef(ncid);
    
  6. Write the data from the MATLAB workspace into the variable in the NetCDF file, using the netcdf.putVar function. Note that the data in the workspace is of class double but the variable in the NetCDF file is of type NC_BYTE. The MATLAB NetCDF functions automatically do the conversion.

    netcdf.putVar(ncid,varid,my_data);
    
  7. Close the file, using the netcdf.close function.

    netcdf.close(ncid);
    
  8. Verify that the data was written to the file by opening the file and reading the data from the variable into a new variable in the MATLAB workspace. Because the variable is the first variable in the file (and the only one), you can specify 0 (zero) for the variable ID—identifiers are zero-based indexes.

    ncid2 = netcdf.open('my_file.nc','NC_NOWRITE');
    
    data_in_file = netcdf.getVar(ncid2,0)
    
    data_in_file =
    
        0
        1
        2
        3
        4
        5
        6
        7
        8
        9
        .
        .
        .
    

    Because you stored the data in the file as NC_BYTE, MATLAB reads the data from the variable into the workspace as class int8.

Was this topic helpful?