Using the C++ Math Library    

Indexing Techniques

The following sections describe some common indexing task and how to accomplish them.

Duplicating a Row or Column

You can make duplicate copies of an array row or column in two different ways: an intuitive way and a short way.

Assume that you want to make a matrix that consists of four copies of the first row of a 5-by-5 matrix, for example, the matrix returned by magic(5):

The Intuitive Solution

For the straightforward approach, you use the vertcat() or horzcat() functions in the MATLAB C++ Math Library. (In MATLAB you would use the concatenation operator [].) This approach requires two lines of code (one assignment and one concatenation) or one long line:

The code makes C into a 4-by-5 matrix, using two lines of code. (Don't count the line that declares A.) First, the first row of A is assigned to B. Then vertcat() concatenates B four times into C, producing this result:

The Shortcut

You can accomplish the same task with a single short line.

This code produces the same matrix as the previous code fragment, but does not require the declaration of the intermediate matrix B. The ones() function creates a vector of four 1's, which as a subscript, selects the first row in matrix A four times.

You can use this trick to duplicate columns instead of rows by switching the positions of the calls to ones() and colon():

This creates a 5-by-4 matrix containing duplicates of the first column of A:


 Deleting Elements from a Structure Array Concatenating Subscripts