Using the C Math Library | ![]() ![]() |
Displaying MATLAB Arrays
To output an array to the display, use the MATLAB C Math Library mlfPrintMatrix()
routine. This routine can display all types of MATLAB arrays of any dimension. The following code fragment creates a 2-by-2 matrix filled with ones and then uses mlfPrintMatrix()
to output the array to the screen.
mxArray *A = NULL; mlfAssign(&A,mlfOnes(mlfScalar(2),mlfScalar(2),NULL)); mlfPrintMatrix(A); mxDestroyArray(A);
This code produces the following output.
1 1 1 1
When used with a cell array, the mlfPrintMatrix()
output includes the type and size of the array stored in each cell but not the data in the array (except for scalar arrays and character arrays). To view the data in each cell in a cell array, you must use the mlfCelldisp()
routine. See Displaying the Contents of a Cell Array for more information.
Formatting Output
You can also create formatted array output using the mlfFprintf()
routine. This routine allows you to create your own output formats and applies these formats to all the elements in a MATLAB array. For example, if you specify the format string "%d"
, mlfFprintf()
prints out each element in an array as an integer.
Note
Do not confuse mlfFprintf() with mlfPrintf() . mlfFprintf() can format MATLAB arrays; mlfPrintf() does not. mlfPrintf() is the same as the standard C printf() routine except that it directs output to the MATLAB print handler. For more information about print handlers, see Chapter 8, Handling Errors and Writing a Print Handler..
|
The following code prints the 2-by-2 array, A
, created in the previous section to the display.
mxArray *A = NULL; mlfAssign(&A,mlfOnes(mlfScalar(2),mlfScalar(2),NULL)); mlfFprintf(mlfScalar(1), /* stdout */ mxCreateString("Array A = %d\n"), /* format string */ A, /* array */ NULL);
This code produces the following output, illustrating how mlfFprintf()
applies the format to each element in an array.
array A = 1 array A = 1 array A = 1 array A = 1
![]() | Allocating and Freeing MATLAB Arrays | Determining Array Type | ![]() |