Display Output in MATLAB Command Window - MATLAB & Simulink (original) (raw)
Main Content
MEX functions can display output in the MATLABĀ® command window. However, some compilers do not support the use ofstd::cout
in MEX functions. Another approach is to usestd::ostringstream
and the MATLABfprintf 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
anddouble
. 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
namedstream
. - Insert the data to display into the
stream
. - Call
displayOnMATLAB
with thestream
object.
The displayOnMATLAB
member function passes the stream contents tofprintf
and then clears the stream buffer. You can reuse thestream
object for subsequent calls todisplayOnMATLAB
.
#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
feval | matlab::data::ArrayFactory