Using the C++ Math Library    

Writing Efficient Programs

The general rule for writing efficient programs with this library is to use scalars wherever possible.

Operations on integers and doubles are at least one order of magnitude faster than the corresponding operations on arrays. The use of scalars has the most impact in indexing and arithmetic expressions. Wherever possible, use integers instead of 1-by-1 arrays in indexing expressions, and doubles rather than 1-by-1 arrays in arithmetic expressions.

However, do not let the preceding comments discourage you from using the full power of the interface. Using the efficiency of scalars helps your code run faster, but you should not base your designs on it. Your design and development time are worth much more than a few CPU-cycles.

The table below demonstrates several cases where you can use doubles and integers to improve the efficiency of your programs.

Table 2-1: Using Scalars for Efficiency 
MATLAB code
Naive C++ Translation
Efficient C++ Translation
Reasons
C = A(3) * B(4);
mwArray A, B, C;
C = A(3) * B(4);
double C;
mwArray A, B;
C = A(3) * B(4);
Use of double as result.
n = max(size(A))
A(n) = n*n;
mwArray n, A;
n = max(size(A));
A(n) = n*n;
int n;
mwArray A;
n = max(size(A));
A(n) = n*n;
Use of integer as index. Integer rather than matrix multiplication.


 Example Program: Writing Simple Functions (ex4.cpp) Learning More