Using the C++ Math Library    

Summary of Library Calling Conventions

Several rules express the formal mapping between the MATLAB and C++ calling conventions:

  1. If there is only one output argument, the syntax of the MATLAB C++ Math Library is identical to the interpreted MATLAB syntax.

    For example, the MATLAB statement A = eig(C); translates to the identical C++ statement A = eig(C);.

  1. If there is more than one output argument, the first output argument becomes the function return value. The others are passed as output arguments and are each prefixed with an &. They precede the input arguments in the argument list.

    For example, the MATLAB function call [ U, S, V ] = svd(X) has three output arguments, U, S, and V, and one input argument X. The corresponding call in C++ is U = svd(&S, &V, X). Note that the two output arguments in the argument list must be prefixed with an &, as the C++ library requires output arguments to be passed by reference.

  1. If there is a variable-length output argument list, you must construct an mwVarargout object that can represent any number of arguments. The constructor takes 32 arguments, the first of which can be another mwVarargout object, allowing you to create any length output argument list.
  2. If there are more than 32 input arguments, you must construct an mwVarargin object that can itself represent 32 arguments, the first of which can be another mwVarargin object, allowing you to create any length argument list.

The following table summarizes the mapping between interpreted MATLAB functions and the same functions in the MATLAB C++ Math Library.

Table 5-1: MATLAB and C++ Function Calling Conventions 
MATLAB Calling Sequence
C++ Calling Sequence
Input/Output Count
A = eig(C);
A = eig(C);
one input
one output
L = tril(X, k);
L = tril(X, k);
two inputs
one output
[ A, B ] = eig(C);
A = eig(&B, C);
one input
two outputs
[ U, S, V ] = svd(X);
U = svd(&S, &V, X);
one input
three outputs
[ U, S, V ] = svd(X, 0);
U = svd(&S, &V, X, 0);
two inputs
three outputs
B = cat(2,A1,A2,A3,A4,A5,A6);
B = cat(2,A1,A2,A3,A4,A5,A6);
seven inputs
one output
[d1,d2,d3,d4] = size(X);
size(
mwVarargout(d1, d2, d3, d4),
  X);
one input
four outputs

Exceptions to the Calling Conventions

The load() and save() functions do not follow the standard calling conventions for the library. For information about load() and save(), see Importing and Exporting MAT-File Data in Chapter 8.


 Passing Any Number of Outputs Example Program: Calling Library Functions (ex2.cpp)