在 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
另请参阅
feval | matlab::data::ArrayFactory