Using the C Math Library    

Example Program: Creating Numeric Arrays (ex1.c)

This program creates two arrays and then prints them. The code demonstrates only one of the ways to create an array. Each of the numbered sections of code is explained in more detail below. You can find the code for this example in the <matlab>/extern/examples/cmath directory on UNIX systems and in the <matlab>\extern\examples\cmath directory on PCs, where <matlab> represents the top-level directory of your installation.

The numbered items in the list below correspond to the numbered comments in the code example:

  1. Include "matlab.h". This file contains the declaration of the mxArray data structure and the prototypes for all the functions in the library. stdlib.h contains the definition of EXIT_SUCCESS.
  2. Declare two static arrays of real numbers that are subsequently used to initialize matrices. The data in the arrays is interpreted by the MATLAB C Math Library in column-major order. The first array, real_data, stores the data for the real part of both matrices, and the second, cplx_data, stores the imaginary part of mat1.
  3. Create two full matrices with mlfDoubleMatrix(). mlfDoubleMatrix() takes four arguments: the number of rows, the number of columns, a pointer to a standard C array of data to initialize the real part of the array and a pointer to a C array of data to initialize the imaginary part, if present. mlfDoubleMatrix()allocates an mxArray structure and storage space for the elements of the matrix, initializing each entry in the matrix to the values specified in the initialization arrays. The first matrix, mat0, does not have an imaginary part. The second matrix, mat1, has an imaginary part. mat0 has two rows and three columns, and mat1 has three rows and two columns.
  4. Print the matrices. mlfPrintMatrix() calls the installed print handler, which in this example is the default print handler. See the section Chapter 8 for details on writing and installing a print handler.
  5. Free the matrices.

The program produces this output:


 Initializing a Numeric Array with Data Sparse Matrices