Main Content

Pass std::vector Parameter

When you pass a clib array directly as a parameter to a C++ function that expects an std::vector input, MATLAB® converts the elements and the size of the clib array to an std::vector argument. The number of dimensions of the passed array must match the expected dimensions of the parameter.

Display Help for Interface

Suppose that you have an interface with the definition for a function fcn. To run this example, follow the instructions in Build Interface for std::vector Example to generate a MATLAB interface named libvector.

When you display help for libvector, you see that function fcn takes an std::vector of type double.

help clib.libvector.fcn
fcn -  clib.libvector.fcn Representation of C++ function fcn.

  clib.libvector.fcn(doubleVec)
    Input Arguments
      doubleVec      vector clib.array.libvector.Double

The corresponding MATLAB type is a vector of clib.array.libvector.Double with elements of type clib.libvector.Double .

Call Function in MATLAB

Call clibArray to create a 1-D clib array of type clib.libvector.Double and pass it to fcn.

arr1d = clibArray("clib.libvector.Double",[3]);
arr1d.Dimensions
ans = 3
clib.libvector.fcn(arr1d)

However, if you pass a 2-D array, MATLAB returns an error because the dimensions do not match.

arr2d = clibArray("clib.libvector.Double",[2 3]);
arr2d.Dimensions
ans = 1×2    
     2     3
clib.libvector.fcn(arr2d)
Error using clib.libvector.fcn
No method 'clib.libvector.fcn' with matching signature found.

Build Interface for std::vector Example

This C++ code defines a function that takes an std::vector of type double.

#include <vector>
void fcn(std::vector<double> doubleVec){};

To run the example, save this code in a header file named vector.hpp, then generate a MATLAB interface named libvector following the instructions in Header-Only HPP File.

Library ArtifactsMATLAB Interface libnameMATLAB Help

Header file vector.hpp

clib.libvector

>> help clib.libvector

See Also

Topics