Using the C++ Math Library    

Initializing a Numeric Array with Data

Using concatenation to build large arrays can become cumbersome. As an alternative, you can put the data into a standard C++ array and pass it to the mwArray matrix constructor, specifying the size and shape of the array. (See page 3-6 for more information.) For complex numbers, pass the imaginary part to the constructor in a separate C++ array. This method of creating an array is more efficient than using concatenation.

Column-Major versus Row-Major Storage

When you are initializing a MATLAB array with a standard C++ array, store the C++ array data in column-major order. For example, to create a 2-by-3 array (two rows, three columns) containing 1 2 3 in the first row and 4 5 6 in the second, you would use a six-element, one-dimensional C++ array with the elements listed in column-major order:

To list the data in an array in column-major order, read down the columns, from the left-most column to the right-most column. The three columns of this array are 1 4, 2 5, and 3 6.

Using Row-Major Data to Create a Column-Major Array

In some cases, specifying a C++ array in column-major order is inconvenient. An additional function, row2mat(), creates a matrix from a C++ array that stores its data in row-major order. Rewriting the above example to use row2mat() yields this code:

The row2mat function takes an optional fourth argument used for creating complex arrays. The fourth argument points to a C++ array of doubles the same size as the third argument. This fourth argument contains the complex values for the mwArray.

Using Scalar Expansion to Fill an Array with Values

If you used the MATLAB : operator as a wildcard in an indexed assignment statement, the MATLAB scalar expansion capability fills all the elements on the same dimension as the target assignment with the value specified.

The following C++ example uses the colon wildcard in the indexing subscript. The example creates a three-dimensional array, filling the second page of the array with the value specified.


 Creating Numeric Arrays Example Program: Creating Arrays and Array I/O (ex1.cpp)