Main Content

Evaluate MATLAB Statements from C++

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 MATLAB eval function. The MATLABEngine::eval and MATLABEngine::evalAsync functions do not return the results of evaluating the MATLAB statement.

Use MATLABEngine::eval and MATLABEngine::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.

  • These functions pass statements to MATLAB in as a matlab::engine::String.

  • Convert an std::string to a matlab::engine::String using the u"…" literal or the utility function matlab::engine::convertUTF8StringToUTF16String.

  • The input arguments named in the string must exist in the MATLAB workspace.

  • You can assign the results of the evaluation to variables within the statement string. The variable that you assign in the statement is created in the MATLAB base workspace.

  • MATLAB does not require you to initialize the variables created in the statement.

  • You can store the standard output from MATLAB functions and error messages in stream buffers.

Evaluate Mathematical Function in MATLAB

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

  • Evaluate a mathematical function over a specified domain using meshgrid and exp.

  • Create a graph of the function using surf.

  • Export the graph to a JPEG file using print.

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

Related Topics