Using the C++ Math Library    

Selecting a Matrix

Use two vector indices or a vector index and a matrix index to extract a matrix. You can use the function horzcat(), vertcat(), or colon() to make the vector or matrix index, or use mwArray variables that contain vectors or matrices.

The indexing code iterates over two vector indices in a pattern similar to a doubly nested for-loop:

For each of the indicated rows, this operation selects the column elements at the specified column positions. For example,

selects the first, third, and second (in that order) elements from rows 1 and 2, yielding:

Notice that the result has two rows and three columns. The size of the result matrix matches the size of the index vectors: the row index had two elements, the column index had three elements, so the result is 2-by-3.

The two-dimensional indexing routines treat a matrix index as one long vector, moving down the columns of the matrix. The loop for a subscript composed of a matrix in the row position and a vector in the column position works like this:

For example, let the matrix B equal:

Then the expression A(B, horzcat(1, 2)) selects the first, second, first, and third elements of columns 1 and 2:

Note that the result has two columns because horzcat(1, 2) has two columns.

Selecting Entire Rows and Columns

Use the colon() index and a vector or matrix index to select multiple rows or columns from a matrix. For example,
A(horzcat(2, 3), colon()) selects all the elements in rows 2 and 3:

You can use colon() in the row position as well. For example, the expression A(colon(), horzcat(3, 1)) selects all the elements in columns 3 and 1, in that order:

Subscripts of this form make duplicating the rows or columns of a matrix easy. See the Duplicating a Row or Column to learn another technique for duplicating rows and columns.

Selecting an Entire Matrix

Using the colon() index as both the row and column index selects the entire matrix. Although this usage is valid, referring to the matrix itself without subscripting is much easier.


 Selecting a Vector of Elements Extending Two-Dimensional Indexing to N Dimensions