我在for
中有一个mexFunction
循环,该循环在每次迭代时显示一些信息。考虑以下简单代码,它将在MATLAB命令窗口中打印100行,并在每次迭代时更新:
#include "mex.h"
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
/* The gateway function */
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
int numiters = 100;
/* initialize random seed: */
srand(time(NULL));
for (int iter = 1; iter <= numiters; ++iter)
{
int rand_num = rand() % 100 + 1;
/* Print info in matlab */
std::ostringstream buffer;
buffer << "iter = " << iter << " of " << numiters <<
". random number = " << rand_num << endl;
/* need something similar to clc here */
mexPrintf("%s", buffer.str().c_str());
}
return;
}
在每次迭代中,我希望在调用
mexPrintf()
之前清除MATLAB的命令窗口。我知道我可以使用
mexCallMATLAB
来调用MATLAB的clc
,但是我不确定在每次迭代中调用MATLAB是否非常有效,因此我需要C++固有的解决方案。 最佳答案
我对mexCallMATLAB
效率低下的假设是错误的,这要感谢@Ander Biguri的注意。我使用以下测试代码来比较使用mexCallMATLAB
和不使用mexCallMATLAB(0, NULL, 0, NULL, "clc");
的时间。
TL; DR-时序结果
mean time per iteration = 0.1016885 sec
:mexCallMATLAB(0, NULL, 0, NULL, "clc");
mean time per iteration = 0.0978730 sec
:ioFlush()
细节
测试台总结
码
#include "mex.h"
#include <iostream>
#include <sstream>
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <ctime>
#include <vector>
using namespace std;
extern bool ioFlush(void);
/* The gateway function */
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
int numiters = 500;
/* initialize random seed: */
srand(time(NULL));
std::vector<double> all_times(numiters);
for (int iter = 1; iter <= numiters; ++iter)
{
/* tic */
clock_t begin = clock();
std::vector<int> rand_vec;
for(std::size_t i = 0; i < 1000000; ++i)
rand_vec.push_back( rand() % 100 + 1 );
double vec_mean = 0.0;
for(std::size_t i = 0; i < rand_vec.size(); ++i)
vec_mean += rand_vec[i];
vec_mean /= rand_vec.size();
/* clear screen */
mexCallMATLAB(0, NULL, 0, NULL, "clc");
/* toc */
double time_elapsed = double(clock() - begin) / CLOCKS_PER_SEC;
/* Print data in matlab */
std::ostringstream buffer;
buffer << "iter " << iter << " of " << numiters <<
". random vector mean = " << vec_mean <<
". in " << time_elapsed << "s" << endl;
mexPrintf("%s", buffer.str().c_str());
ioFlush();
all_times[iter] = time_elapsed;
}
double avg_time = 0.0;
for(std::size_t i = 0; i < all_times.size(); ++i)
avg_time += all_times[i];
avg_time /= all_times.size();
mexPrintf("\navg time per iter = %3.7f\n", avg_time);
return;
}
请注意
#pragma comment(lib, "libmwservices.lib")
的使用,这是未记录的函数,在每次迭代时都需要更新命令窗口。查看有关它的更多详细信息here。编译
mex yourFile.cpp -lmwservices
。 关于c++ - 从mex函数清除MATLAB命令窗口,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44290796/