这是MATLAB自带的例子,我在WindowsXP(SP2), MATLAB R2007b,
VC6.0下实现。
具体的步骤是:
1). 设置系统环境变量path,path里面要包括MATLAB的exe,
dll那个路径
%MATLAB_PATH%\bin\win32
只要MATLAB是正确安装,它应该会自动配置path环境变量的。
右击我的电脑->属性->高级->环境变量->系统变量
双击path
path值应该有以下两个值,中间是分号
d:\MATLABR2007b\bin;d:\MATLABR2007b\bin\win32
2). 设置VC的路径
运行VC,转到options
include增加MATLAB的include路径
%MATLAB_PATH%\extern\include
lib增加%MATLAB_PATH%\extern\lib\win32\microsoft
这一步以后都不用做了。
3).
在VC中新建一个console项目(也可以是win32,mfc等其他项目),项目的link输入增加libeng.lib和libmx.lib(每个工程都要添加,否则编译不能通过)
4). main函数的代码:
#include
#include
#include
#include "engine.h"
#define BUFSIZE 256
int main()
{
Engine *ep;
mxArray *T = NULL, *result = NULL;
char buffer[BUFSIZE+1];
double time[10] = { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0,
9.0 };
if (!(ep = engOpen("\0"))) {
fprintf(stderr, "\nCan't start MATLAB engine\n");
return EXIT_FAILURE;
}
T = mxCreateDoubleMatrix(1, 10, mxREAL);
memcpy((void *)mxGetPr(T), (void *)time, sizeof(time));
engPutVariable(ep, "T", T);
engEvalString(ep, "D = .5.*(-9.8).*T.^2;");
engEvalString(ep, "plot(T,D);");
engEvalString(ep, "title('Position vs. Time for a falling
object');");
engEvalString(ep, "xlabel('Time (seconds)');");
engEvalString(ep, "ylabel('Position (meters)');");
printf("Hit return to continue\n\n");
fgetc(stdin);
printf("Done for Part I.\n");
mxDestroyArray(T);
engEvalString(ep, "close;");
buffer[BUFSIZE] = '\0';
engOutputBuffer(ep, buffer, BUFSIZE);
while (result == NULL) {
char str[BUFSIZE+1];
printf("Enter a MATLAB command to evaluate. This command
should\n");
printf("create a variable X. This program will then
determine\n");
printf("what kind of variable you created.\n");
printf("For example: X = 1:5\n");
printf(">> ");
fgets(str, BUFSIZE, stdin);
engEvalString(ep, str);
printf("%s", buffer+2);
printf("\nRetrieving X...\n");
if ((result = engGetVariable(ep,"X")) == NULL)
printf("Oops! You didn't create a variable X.\n\n");
else {
printf("X is class %s\t\n", mxGetClassName(result));
}
}
printf("Done!\n");
mxDestroyArray(result);
engClose(ep);
return EXIT_SUCCESS;
}
编译运行,等一会儿会有一个MATLAB图形窗口弹出。