Main Content

MATLAB コマンド ウィンドウの出力を C++ にリダイレクト

MATLAB® は、エラー メッセージおよびステートメントからの出力を MATLAB コマンド ウィンドウに表示します。この出力を C++ プログラムにリダイレクトするには、文字列バッファーを使用してこの出力を取得し、メンバー関数fevalfevalAsynceval、またはevalAsyncを指定して返します。

C++ エンジン プログラムを設定およびビルドする方法の詳細については、C++ エンジン プログラムのビルド要件を参照してください。

画面出力のリダイレクト

このサンプル コードは、MATLAB の 2 つのステートメントを評価します。これらのステートメントは、MATLAB ワークスペースに 3 つの変数を作成します。このコードが MATLAB 関数 whos を呼び出し、これによって MATLAB コマンド ウィンドウに現在のワークスペース変数が表示されます。MATLABEngine::eval への呼び出しでバッファーへのポインターを渡すことにより、文字列バッファーの MATLAB 標準出力を取得します。

#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;
}

エラー出力のリダイレクト

このサンプル コードは、すべての変数を MATLAB ワークスペースから削除した後で変数を参照することにより、MATLAB エラーを発生させます。メンバー関数 MATLABEngine::eval に渡された文字列バッファーが try/catch コード ブロック内にあるエラー メッセージを取得します。

#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;
    }
}

参考

| | |

関連するトピック