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)
:
17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
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:
mwArray A = magic(5); mwArray B = A(1,colon()); mwArray C = vertcat(B, B, B, B);
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:
17 24 1 8 15 17 24 1 8 15 17 24 1 8 15 17 24 1 8 15
The Shortcut
You can accomplish the same task with a single short line.
mwArray A = magic(5); mwArray C = A(ones(1,4), colon());
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()
:
mwArray C = A(colon(), ones(1,4));
This creates a 5-by-4 matrix containing duplicates of the first column of A
:
17 17 17 17 23 23 23 23 4 4 4 4 10 10 10 10 11 11 11 11
![]() | Deleting Elements from a Structure Array | Concatenating Subscripts | ![]() |