Using the C Math Library | ![]() ![]() |
Selecting a Vector
Use a vector index to select multiple elements from an array. For example,
mlfIndexRef(A, "(?)",
mlfHorzcat(mlfScalar(2), mlfScalar(5), mlfScalar(8), NULL))
performs the same operation as A([2 5 8])
in MATLAB and selects the second, fifth and eighth elements of the matrix A
:
2 5 8
Because the index is a 1-by-3 row vector, the result is also a 1-by-3 row vector.
mlfAssign(&B, mlfIndexRef(A, "(?)",
mlfVertcat(mlfScalar(2), mlfScalar(5), mlfScalar(8), NULL)));
selects the same elements of A
, but returns the result as a column vector because the call to mlfVertcat()
produced a column vector:
2 5 8
A([2;5;8])
in MATLAB performs the same operation. Note the semicolons.
Specifying a Vector Index with mlfEnd()
Sometimes you don't know how large an array is in a particular dimension, but you want to perform an indexing operation that requires you to specify the last element in that dimension. In MATLAB, you can use the end
function to refer to the last element in a given dimension.
For example, A(6:end)
selects the elements from A(6)
to the end of the array. The MATLAB C Math Library's mlfEnd()
function corresponds to MATLAB's end()
function. Given an array, a dimension (1 = row , 2 = column, 3 = page, and so on), and the number of indices in the subscript, mlfEnd()
returns (as a 1-by-1 array) the index of the last element in the specified dimension. You can then use that scalar array to generate a vector index.
Given the row dimension for a vector or scalar array, mlfEnd()
returns the number of columns. Given the column dimension for a vector or scalar array, it returns the number of rows. For a matrix, mlfEnd()
treats the matrix like a vector and returns the number of elements in the matrix.
Note that the number of indices in the subscript corresponds to the number of index arguments that you pass to mlfIndexRef()
.
This C code selects all but the first five elements in matrix A
, just as A(6:end)
does in MATLAB.
mxArray *end_index=NULL, *B=NULL; mlfAssign(&end_index, mlfColon(mlfScalar(6), mlfEnd(A, mlfScalar(1), mlfScalar(1)), NULL)); mlfAssign(&B, mlfIndexRef(A, "(?)", end_index));
The second argument, mlfScalar(1)
, to mlfEnd()
identifies the dimension where mlfEnd()
is used, here the row dimension. The third argument, mlfScalar(1),
indicates the number of indices in the subscript; for one-dimensional indexing, it is always one. This code selects these elements from matrix A
:
6 7 8 9
![]() | Selecting a Single Element | Selecting a Matrix | ![]() |