//engOpen():打开MATLAB引擎;
//mxCreateDoubleMatrix():创建MATLAB变量矩阵;
//mxGetPr():获取MATLAB变量的地址值;
//memcpy():将C语言中的变量值赋值给MATLAB变量;
//engPutVariable():将创建的MATLAB变量放至MATLAB工作空间;
//engEvalString():执行字符串形式的MATLAB语句;
//mxDestroyArray():释放MATLAB中创建的变量,释放内存;
//engClose():关闭MATLAB引擎。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include “engine.h” //引擎头文件,识别matlab引擎函数
#pragma comment( lib, “libeng.lib”)
#pragma comment( lib, “libmx.lib”)
#pragma comment( lib, “libmat.lib”)
int main(void)
{
Engine* ep;//定义matlab引擎指针
if (!(ep = engOpen("\0")))
{
fprintf(stderr, "\nCan't start MATLAB engine\n");//测试是否matlab引擎启动成功
return EXIT_FAILURE;
}
const double PI = 3.1415926;
int f1 = 20 * 10 ^ 6; int f2 = 25 * 10 ^ 6; int f3 = 20 * 10 ^ 6 + 1 * 10 ^ 4;
int T1 = 1 / f1; int T2 = 1 / f2; int T3 = 1 / f3;
int w1 = 6.28 / T1; float w2 = 6.28 / T2; float w3 = 6.28 / T3;
float ts = 0.0000005;
int Nsample = 100;
double* t = new double[Nsample];
for (int i = 0; i < Nsample; i++)
{
//t[i] = i * 2 * PI / Nsample;
t[i] = i * (w1 * ts) / Nsample;
}
mxArray* T = NULL, * result = NULL; //mxArray 为不同类型的变量的同一种数据结构,
T = mxCreateDoubleMatrix(1, Nsample, mxREAL);//数组建立的函数形式,,,参数表示:行数、列数、实数或者复数
memcpy((void*)mxGetPr(T), (void*)t, Nsample * sizeof(t[0]));
engPutVariable(ep, "T", T); // put data to engine
//engEvalString(ep, "Y=5*sin((w1)*T);");
// execute matlab operations
//engEvalString(ep, "Y=sin(T);");
engEvalString(ep, "Y=5*sin(T);");//向matlab发送命令字符串,参数ep为函数 engopen返回的引擎指针,字符串string为要matlab执行的命令
engEvalString(ep, "plot(T,Y);");
//engEvalString(ep, "title('y=sin(t)');");
//engEvalString(ep, "xlabel('t');");
//engEvalString(ep, "ylabel('y');");
printf("Hit return to continue\n");
fgetc(stdin);
// clean operation(don't forget!!!)
mxDestroyArray(T);
engEvalString(ep, "close;");
// close engine
engClose(ep);
return EXIT_SUCCESS;
}