Using the C Math Library | ![]() ![]() |
Selecting a Matrix
Use two vector indices, or a vector and a matrix index, to extract a matrix. You can use the function mlfHorzCat()
, mlfVertcat()
, or mlfCreateColonIndex()
to make each vector or matrix index, or use mxArray
variables that contain vectors or matrices returned from other functions.
The indexing code iterates over both vector indices in a pattern similar to a doubly nested for
-loop:
for each element I in the row index for each element J in the column index select the matrix element A(I,J)
For each of the indicated rows, this operation (A([1 2], [1 3 2])
in MATLAB) selects the column elements at the specified column positions. For example,
mlfAssign(&B, mlfIndexRef(A, "(?,?)", mlfHorzcat(mlfScalar(1), mlfScalar(2), NULL), mlfHorzcat(mlfScalar(1), mlfScalar(3), mlfScalar(2), NULL)));
selects the first, third, and second (in that order) elements from rows 1 and 2, yielding:
1 7 4 2 8 5
Notice that the result has two rows and three columns. The size of the result matrix always matches the size of the index vectors: the row index had two elements; the column index had three elements. The result is 2-by-3.
The 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 each column I in the row index matrix B for each row J in the Ith column of B for each element K in the column index vector select the matrix element A(B(I,J), K)
For example, let the matrix B
equal:
1 1 2 3
mlfIndexRef(A, "(?,?)", B,
mlfHorzcat(mlfScalar(1), mlfScalar(2), NULL))
performs the same operation as A(B,[1 2])
in MATLAB and selects the first, second, first, and third elements of columns 1 and 2:
1 4 2 5 1 4 3 6
Selecting Entire Rows or Columns
Use a colon index and a vector or matrix index to select multiple rows or columns from a matrix. For example,
mlfIndexRef(A, "(?,?)", mlfHorzcat(mlfScalar(2), mlfScalar(3), NULL), mlfCreateColonIndex())
performs the same operation as A([2 3],:)
in MATLAB and selects all the elements in rows two and three:
2 5 8 3 6 9
You can use the colon index in the row position as well. For example, the expression
mlfAssign(&B, mlfIndexRef(A, "(?,?)", mlfCreateColonIndex(), mlfHorzcat(mlfScalar(3), mlfScalar(1), NULL)));
performs the same operation as A(:,[3 1]
) in MATLAB and selects all the elements in columns 3 and 1, in that order:
7 1 8 2 9 3
Subscripts of this form make duplicating the rows or columns of a matrix easy.
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 | ![]() |