Using the C++ Math Library | ![]() ![]() |
Concatenating Subscripts
In MATLAB, you apply an index operation to a variable. You cannot apply an index to the result of a function call or to the result of an arithmetic operation, without first assigning the result to an array variable.
In C++, however, you can apply an index to any object of type mwArray
or of a type that can be automatically converted into an mwArray,
including mwArray
results from function calls, arithmetic operations and indexing operations. Being able to perform an indexing operation without having to declare a temporary variable first is very convenient.
This is a notational convenience only; your code does not run faster.
Applying a Subscript to the Result of a Function Call
You can easily compose function calls using this technique. Applying a subscript to the result of a function call lets you extract a subarray from the result and pass that result directly to a second function, without having to assign the result to a variable first.
For example, this code extracts a 3-by-3 array from a 10-by-10 magic square, and passes the 3-by-3 array to sqrt()
.
mwIndex i = ramp(4,6); mwArray A = sqrt(magic(10)(i,i));
Applying a Subscript to the Result of an Arithmetic Operation
You can apply a subscript to the result of an arithmetic operation. For example, this code multiplies two random 4-by-4 arrays, A
and B
, and extracts the (2,2)
element of the result into a double precision floating-point scalar, x
.
mwArray A = rand(4), B = rand(4); double x = (A * B)(2,2);
By moving the calls to rand()
to the second line, you can rewrite this example in one line:
double x = (rand(4) * rand(4))(2,2);
This technique works with logical operations as well.
![]() | Indexing Techniques | C++ and MATLAB Indexing Syntax | ![]() |