直接在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;
}