Main Content

MATLAB コマンド ウィンドウでの出力の表示

MEX 関数は、MATLAB® コマンド ウィンドウに出力を表示できます。ただし、コンパイラによっては、MEX 関数での std::cout の使用がサポートされていない場合があります。別のアプローチとしては、std::ostringstream と MATLAB 関数 fprintf を使用して、MATLAB コマンド ウィンドウにテキストを表示します。

次の MEX 関数は単純に、入力として渡されたテキスト値と数値を返します。引数は char および double であるとします。簡略化のため、エラー チェックは省略しています。

MEX 関数が MATLAB コマンド ウィンドウにテキストを表示する方法は次のとおりです。

  • stream という名前の std::ostringstream のインスタンスを作成します。

  • stream に表示するデータを挿入します。

  • stream オブジェクトを指定して displayOnMATLAB を呼び出します。

メンバー関数 displayOnMATLAB は、ストリームの内容を fprintf に渡し、その後ストリーム バッファーをクリアします。displayOnMATLAB への後続の呼び出しで、stream オブジェクトを再利用できます。

#include "mex.hpp"
#include "mexAdapter.hpp"

using matlab::mex::ArgumentList;
using namespace matlab::data;

class MexFunction : public matlab::mex::Function {
    // Pointer to MATLAB engine to call fprintf
    std::shared_ptr<matlab::engine::MATLABEngine> matlabPtr = getEngine();

    // Factory to create MATLAB data arrays
    ArrayFactory factory;

    // Create an output stream
    std::ostringstream stream;
public:
    void operator()(ArgumentList outputs, ArgumentList inputs) {
        const CharArray name = inputs[0];
        const TypedArray<double> number = inputs[1];
        stream << "Here is the name/value pair that you entered." << std::endl;
        displayOnMATLAB(stream);
        stream << name.toAscii() << ": " << double(number[0]) << std::endl;
        displayOnMATLAB(stream);
    }

    void displayOnMATLAB(std::ostringstream& stream) {
        // Pass stream content to MATLAB fprintf function
        matlabPtr->feval(u"fprintf", 0,
            std::vector<Array>({ factory.createScalar(stream.str()) }));
        // Clear stream buffer
        stream.str("");
    }
};

MATLAB から MEX 関数 (この例では streamOutput.cpp という名前) を呼び出すと、次の結果が得られます。

mex streamOutput.cpp
streamOutput('Total',153)
Here is the name/value pair that you entered.
Total: 153

参考

|

関連するトピック