Using the C++ Math Library | ![]() ![]() |
Example - Array Stream I/O (ex1.cpp)
This example illustrates the use of stream I/O to read in and print out a MATLAB array. You can find the code for this example in the <matlab>/extern/examples/cppmath
directory on UNIX systems and in the <matlab>\extern\examples\cppmath
directory on PCs, where <matlab>
represents the top-level directory of your installation. See Building C++ Applicationsfor information about building and running the example program.
In the example, note that the array input format is the same as the array output format. Data written out by a program can be easily read back in by a program. For more information about this format, see the Stream I/O Format Definitions.
// ex1.cpp
#include <stdlib.h>
#include "matlab.hpp" // #1
static double data[] = { 1, 2, 3, 4, 5, 6 };
int main(void)
{
// Create two matrices.
mwArray mat0(2, 3, data);
mwArray mat1(3, 2, data);
// Print the matrices.
cout << mat0 << endl; // #2
cout << mat1 << endl;
// Read a matrix from standard in, then print the matrix to
// standard out.
cout << "Please enter a matrix: " << endl; // #3
cin >> mat1;
cout << mat1 << endl; // #4
return (EXIT_SUCCESS);
}
The numbered items in the list below correspond to the numbered comments in the code example:
matlab.hpp
declares the MATLAB C++ Math Library's data types and functions. matlab.hpp
includes iostream.h
, which declares the input and output streams cin
and cout
. stdlib.h
contains the definition of EXIT_SUCCESS
.
cout
. By default, objects printed with cout
appear on the screen, though you can redirect the output to a file.
mat1
using the C++ standard input stream, cin
. The matrix does not need to be the same size as the matrix already stored in mat1
. The input operator >>
creates a new matrix and assigns that matrix to mat1
. UNIX and PC systems read from the terminal by default; you can redirect them to read from an input file.
The program prints out the two matrices, mat0
and mat1
, and then prompts the user to input an array.
[ 1 3 5 ; 2 4 6 ] [ 1 4 ; 2 5 ; 3 6 ] Please enter a matrix:
To enter a matrix, first type in a left bracket ([
) character, and then enter a series of numbers. You can insert semicolons at any point to create a two-dimensional matrix. End your matrix by typing a right bracket (]
) character. Each row must contain the same number of columns. Spaces, tabs, and carriage returns are ignored. For complete information about input and output formats, see the section Stream I/O Format Definitions.
For example, if you type in [ 1 2; 3 4 ]
, the program prints it.
[ 1 2; 3 4 ]
Note that the output format is the same as the input format, enabling the output from one program to be used as the input to another. Because each matrix is delimited by [
and ]
, input files or streams can contain more than one matrix.
![]() | Overview | Stream I/O Format Definitions | ![]() |