Main Content

Displaying Output in MATLAB Command Window

MEX functions can display output in the MATLAB® command window. However, some compilers do not support the use of std::cout in MEX functions. Another approach is to use std::ostringstream and the MATLAB fprintf function to display text in the MATLAB command window.

The following MEX function simply returns the text and numeric values that are passed to the function as inputs. The arguments are assumed to be a char and double. Error checking is omitted for simplicity.

Here is how the MEX function displays text in the MATLAB command window:

  • Create an instance of std::ostringstream named stream.

  • Insert the data to display into the stream.

  • Call displayOnMATLAB with the stream object.

The displayOnMATLAB member function passes the stream contents to fprintf and then clears the stream buffer. You can reuse the stream object for subsequent calls to displayOnMATLAB.

#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("");
    }
};

Calling the MEX function (named streamOutput.cpp in this example) from MATLAB produces the following result.

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

See Also

|

Related Topics