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.

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

  1. Include header files. 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.
  2. Print the matrices using the C++ standard output stream, cout. By default, objects printed with cout appear on the screen, though you can redirect the output to a file.
  3. Prompt the user to type in a matrix. Read the matrix into 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.
  4. Print the newly read matrix.

    Output

The program prints out the two matrices, mat0 and mat1, and then prompts the user to input an array.

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.

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