直接在Visual Studio中运行Matlab固有命令

#include <iostream>
#include"engine.h" // 添加matlab引擎库的头文件 //PATH: D:\Program Files\MATLAB\MATLAB Runtime\v901\runtime\win64
// 包含目录: D:\Program\MATLAB\R2016a\extern\include
// 库目录: D:\Program\MATLAB\R2016a\extern\lib\win64\microsoft
// 附加依赖项: libmat.lib;libeng.lib;libmx.lib;
#pragma comment(lib, "libeng.lib")
#pragma comment(lib, "libmx.lib")
#pragma comment(lib, "libmat.lib") using namespace std; int main()
{
Engine *ep;
// 启动引擎
if (!(ep = engOpen("\0")))
{
fprintf(stderr, "\n打开Matlab引擎失败!\n");
return EXIT_FAILURE;
}
// 执行:
int Nsample = 50; //采样率50Hz,每秒50个点
const double PI = 3.1415926;
double *t = new double[Nsample];
for (int i = 0; i <Nsample; i++) //i是时间,i/N是每个采样点的时间间隔,t[i]=2*PI*t
{
t[i] = i * 2 * PI / Nsample;
}
mxArray *T = NULL, *result = NULL;
T = mxCreateDoubleMatrix(1, Nsample, mxREAL); //新建Double型的矩阵,1行Nsample列
memcpy((void *)mxGetPr(T), (void *)t, Nsample * sizeof(t[0])); //把t中数据拷贝到T中
// 把变量T存入Matlab工作区
engPutVariable(ep, "X", T); //拷贝T到引擎中的X变量 // 执行Matlab命令   
engEvalString(ep, "Y=cos(X);");
engEvalString(ep, "plot(X,Y);");
engEvalString(ep, "title('y=cos(x)');");
engEvalString(ep, "xlabel('x');");
engEvalString(ep, "ylabel('y');");
fgetc(stdin);
// 清除对象,不能漏!
mxDestroyArray(T);
engEvalString(ep, "close;");
// 关闭引擎,不能漏!
engClose(ep); cout << "运行完成" << endl; return 0;
}
05-11 19:23