Main Content

Redirect MATLAB Command Window Output to C++

MATLAB® displays error messages and the output from statements in the MATLAB command window. To redirect this output to your C++ program, use a string buffer to capture this output and return it with the feval, fevalAsync, eval, or evalAsync member function.

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

Redirect Screen Output

This sample code evaluates two statements in MATLAB. These statements create three variables in the MATLAB workspace. The code calls the MATLAB whos function, which displays the current workspace variables in the MATLAB command window. Capture MATLAB standard output in a string buffer by passing a pointer to the buffer with the call to MATLABEngine::eval.

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

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

    // Evaluate statements that create variables
    matlabPtr->eval(u"[X,Y] = meshgrid(-2:.2:2);");
    matlabPtr->eval(u"Z = X.*exp(-X.^2 - Y.^2);");

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

    // Create string buffer for standard output
    typedef std::basic_stringbuf<char16_t> StringBuf;
    std::shared_ptr<StringBuf> output = std::make_shared<StringBuf>();

    // Display variables in the MATLAB workspace
    matlabPtr->eval(u"whos", output);

    // Display MATLAB output in C++
    String output_ = output.get()->str();
    std::cout << convertUTF16StringToUTF8String(output_) << std::endl;
}

Redirect Error Output

This sample code causes a MATLAB error by referencing a variable after clearing all variables from the MATLAB workspace. The string buffer passed to the MATLABEngine::eval member function captures the error message inside a try/catch code block.

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

    using namespace matlab::engine;

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

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

    // Create string buffer for standard output
    typedef std::basic_stringbuf<char16_t> StringBuf;
    std::shared_ptr<StringBuf> error = std::make_shared<StringBuf>();

    // Evaluate statement that causes error
    matlabPtr->eval(u"clear");
    try {
        matlabPtr->eval(u"x + 2;", {}, error);
    }
    catch (...) {
        String error_ = error.get()->str();
        std::cout << convertUTF16StringToUTF8String(error_) << std::endl;
    }
}

See Also

| | |

Related Topics