Evaluate MATLAB Statements from C++ - MATLAB & Simulink (original) (raw)

Main Content

Evaluation of MATLAB Statements

These examples show you how to evaluate MATLAB® statements from C++ using the MATLABEngine::eval and MATLABEngine::evalAsync member functions. These member functions are similar to the MATLABeval function. TheMATLABEngine::eval andMATLABEngine::evalAsync functions do not return the results of evaluating the MATLAB statement.

Use MATLABEngine::eval andMATLABEngine::evalAsync when you do not need to pass arguments from C++ or return values to C++. The statements that you execute with these functions can access variables in the MATLAB workspace.

Here are some things to know about evaluating statements in MATLAB.

Evaluate Mathematical Function in MATLAB

This example uses MATLABEngine::eval to evaluate a series of MATLAB statements. These statements:

Here is the equivalent MATLAB code.

[X, Y] = meshgrid(-2:0.2:2); Z = X .* exp(-X.^2 - Y.^2); surf(Z) print('SurfaceGraph', '-djpeg') currentFolder = pwd;

Here is the C++ code to execute these statements in MATLAB.

#include "MatlabDataArray.hpp"
#include "MatlabEngine.hpp"
#include <iostream>

void evalSurfaceGraph() {
    // Evaluate functions in MATLAB

    using namespace matlab::engine;

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

    // Evaluate commands in MATLAB
    matlabPtr->eval(u"[X, Y] = meshgrid(-2:0.2:2);");
    matlabPtr->eval(u"Z = X .* exp(-X.^2 - Y.^2);");
    matlabPtr->eval(u"surf(Z)");
    matlabPtr->eval(u"print('SurfaceGraph', '-djpeg')");
    matlabPtr->eval(u"currentFolder = pwd;");

    // Get the name of the folder containing the jpeg file
    matlab::data::CharArray currentFolder = matlabPtr->getVariable(u"currentFolder");
    std::cout << "SurfaceGraph.jpg written to this folder: " << 
          currentFolder.toAscii() << std::endl;
}

For information on how to setup and build C++ engine programs, see Requirements to Build C++ Engine Applications.

See Also

matlab::engine::MATLABEngine