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.
/* ex1.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "matlab.h" /* 1 */ static double real_data[] = { 1, 2, 3, 4, 5, 6 }; /* 2 */ static double cplx_data[] = { 7, 8, 9, 10, 11, 12 }; int main() { mxArray *mat0 = NULL; mxArray *mat1 = NULL; mlfEnterNewContext(0, 0); mlfAssign(&mat0, mlfDoubleMatrix(2,3,real_data,NULL)); /* 3 */ mlfAssign(&mat1, mlfDoubleMatrix(3,2,real_data,cplx_data)) mlfPrintMatrix(mat0); /* 4 */ mlfPrintMatrix(mat1); mxDestroyArray(mat0); /* 5 */ mxDestroyArray(mat1); mlfRestorePreviousContext(0, 0); return(EXIT_SUCCESS); }
The numbered items in the list below correspond to the numbered comments in the code example:
"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
.
real_data
, stores the data for the real part of both matrices, and the second, cplx_data
, stores the imaginary part of mat1
.
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.
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.
The program produces this output:
1 3 5 2 4 6 1.0000 + 7.0000i 4.0000 +10.0000i 2.0000 + 8.0000i 5.0000 +11.0000i 3.0000 + 9.0000i 6.0000 +12.0000i
![]() | Initializing a Numeric Array with Data | Sparse Matrices | ![]() |