Using the C++ Math Library    

Passing Optional Output Arguments

MATLAB functions may also have optional or multiple output arguments. For example, you invoke the find() function, which locates nonzero entries in matrices, with one, two, or three output arguments:

In interpreted MATLAB, find() returns one, two or three values. In C++, no function can return more than one value. Therefore, the additional output arrays are passed to find() in the argument list. Output arguments are always pointers to mwArray objects, (mwArray* variables), and they always appear before input arguments in the parameter list.

To accommodate all the combinations of output arguments, there are three overloaded versions of find() in the MATLAB C++ Math Library. Using the MATLAB C++ Math Library, you call find() like this:

k, i, j, v, and X are mwArray objects. You do not need to preallocate k, i, j, or v; when you declare them as mwArray objects, they are appropriately initialized.

Note how easy it is to distinguish input variables from output variables; an ampersand (&) always precedes each output variable. In C++, the & operator, when placed in front of an array, computes the address of, or pointer to, that array. All of the arguments with & placed in front of them are output arguments, corresponding to the variables on the left-hand side of the MATLAB expression.

The general rule for multiple output arguments: use the function return value, an mwArray, as the first output argument; pass all additional output arguments into the function as mwArray* parameters. By convention, output arguments always come first, followed by input arguments. Putting the output arguments first may surprise some C++ programmers because it prevents the use of default values for optional arguments. However, this ordering is more natural for MATLAB programmers, since it keeps the output arguments, which in MATLAB would be on the left-hand side of the assignment operator, as close to the left-hand side as possible.


 Passing Optional Input Arguments Passing Optional Input and Output Arguments