Main Content

Test Your C++ Build Environment

Create C++ Example testFeval

To test your installation and environment for building applications using the MATLAB® engine API for C++, save this C++ code in a file named testFeval.cpp (you can use any name).

#include "MatlabDataArray.hpp"
#include "MatlabEngine.hpp"
#include <iostream>
void callSQRT() {

    using namespace matlab::engine;

    // Start MATLAB engine synchronously
    std::unique_ptr<MATLABEngine> matlabPtr = startMATLAB();

    //Create MATLAB data array factory
    matlab::data::ArrayFactory factory;

    // Define a four-element typed array
    matlab::data::TypedArray<double> const argArray = 
        factory.createArray({ 1,4 }, { -2.0, 2.0, 6.0, 8.0 });

    // Call MATLAB sqrt function on the data array
    matlab::data::Array const results = matlabPtr->feval(u"sqrt", argArray);

    // Display results
    for (int i = 0; i < results.getNumberOfElements(); i++) {
        double a = argArray[i];
        std::complex<double> v = results[i];
        double realPart = v.real();
        double imgPart = v.imag();
        std::cout << "Square root of " << a << " is " << 
            realPart << " + " << imgPart << "i" << std::endl;
    }
}

int main() {
    callSQRT();
    return 0;
}

Select Supported C++ Compiler

From the MATLAB command prompt, type:

mex -setup -client engine C++

Select the installed compiler you want to use. For an up-to-date list of supported compilers, see Supported and Compatible Compilers.

Build testFeval Example

To build the engine application, type this command. The mex command saves the executable file in the current folder.

mex -v -client engine testFeval.cpp

Set Run-Time Environment

Set the platform-specific run-time environment variable:

Operating SystemVariablePath

Windows®

PATH

matlabroot\extern\bin\win64

macOS with Apple silicon

DYLD_LIBRARY_PATH

matlabroot/extern/bin/maca64

macOS with Intel®

DYLD_LIBRARY_PATH

matlabroot/extern/bin/maci64

Linux®

LD_LIBRARY_PATH

matlabroot/extern/bin/glnxa64:matlabroot/sys/os/glnxa64

Run testFeval Example

Call the program:

!testFeval.exe

Here is the output from this program. In this case, MATLAB returns a complex array because one of the numbers in the data array is negative.

Square root of -2 is 0 + 1.41421i
Square root of 2 is 1.41421 + 0i
Square root of 6 is 2.44949 + 0i
Square root of 8 is 2.82843 + 0i

See Also

|

Related Topics