先貼本人調(diào)試通過的代碼:
#pragma comment(lib, "libmx.lib")
//#pragma comment(lib, "libmat.lib")//注銷了也沒關(guān)系
#pragma comment(lib, "libeng.lib")
#include <math.h>
#include "engine.h"
#include <iostream>
using namespace std;
int main()
{
const int N = 50;
double x[N],y[N];
int j = 1;
for (int i=0; i<N; i++) //計(jì)算數(shù)組x和y
{
x[i] = (i+1);
y[i] = sin(x[i]) + j * log(x[i]); //產(chǎn)生-之間的隨機(jī)數(shù)賦給xx[i];
j*= -1;
}
Engine *ep; //定義Matlab引擎指針。
if (!(ep=engOpen(NULL))) //測(cè)試是否啟動(dòng)Matlab引擎成功。
{
cout <<"Can't start Matlab engine!" <<endl;
exit(1);//可以思考下
}
//定義mxArray,為1行,N列的實(shí)數(shù)數(shù)組。
mxArray *xx = mxCreateDoubleMatrix(1,N, mxREAL);
mxArray *yy = mxCreateDoubleMatrix(1,N, mxREAL); //同上。
memcpy(mxGetPr(xx), x, N*sizeof(double)); //將數(shù)組x復(fù)制到mxarray數(shù)組xx中。
memcpy(mxGetPr(yy), y, N*sizeof(double)); //將數(shù)組x復(fù)制到mxarray數(shù)組yy中。
engPutVariable(ep, "xx",xx); //將mxArray數(shù)組xx寫入到Matlab工作空間,命名為xx。
engPutVariable(ep, "yy",yy); //將mxArray數(shù)組yy寫入到Matlab工作空間,命名為yy。
//【特色】向Matlab引擎發(fā)送畫圖命令。plot為Matlab的畫圖函數(shù),參見Matlab相關(guān)文檔。
engEvalString(ep, "plot(xx, yy); ");
mxDestroyArray(xx); //銷毀mxArray數(shù)組xx和yy。(注:Matlab工作空間中的xx、yy變量在這里沒有銷毀)
mxDestroyArray(yy);
cout <<"Press any key to exit!" <<endl;
cin.get();
engClose(ep); //關(guān)閉Matlab引擎。
}
------------------------------------------------------------------------------------------
結(jié)果貼圖:

Matlab中內(nèi)存變量:
xx =
Columns 1 through 22
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
Columns 23 through 44
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
Columns 45 through 50
45 46 47 48 49 50
yy =
Columns 1 through 13
0.8415 0.2162 1.2397 -2.1431 0.6505 -2.0712 2.6029 -1.0901 2.6093 -2.8466 1.3979 -3.0215 2.9851
Columns 14 through 26
-1.6484 3.3583 -3.0605 1.8718 -3.6414 3.0943 -2.0828 3.8812 -3.0999 2.2893 -4.0836 3.0865 -2.4955
Columns 27 through 39
4.2522 -3.0613 2.7037 -4.3892 3.0299 -2.9143 4.4964 -2.9973 3.1272 -4.5753 2.9674 -3.3412 4.6274
Columns 40 through 50
-2.9438 3.5549 -4.6542 2.9294 -3.7665 4.6576 -2.9269 3.9737 -4.6395 2.9381 -4.1744
===========================================================================================
注意事項(xiàng):
1)本程序只需要建立win32控制臺(tái)空項(xiàng)目
2)調(diào)用的是Matlab計(jì)算引擎,故需要有Matlab環(huán)境
3)VS2008中需要在“包含文件”中加入D:\Program Files\MATLAB\R2009b\extern\include(以后本人的Matlab與C混合編程例子中將不再給出此注意點(diǎn))
4)VS2008中需要在“庫(kù)文件”中加入D:\Program Files\MATLAB\R2009b\extern\lib\win32\microsoft(以后本人的Matlab與C混合編程例子中將不再給出此注意點(diǎn))
5)系統(tǒng)變量中加入三個(gè)路徑:D:\Program Files\MATLAB\R2009b\runtime\win32;D:\Program Files\MATLAB\R2009b\bin\win32;D:\Program Files\MATLAB\R2009b\extern\lib\win32\microsoft;注銷后重進(jìn)系統(tǒng),以使路徑生效
6)應(yīng)該不會(huì)再有問題?!救绻€有其他小問題(Main、Unicode等)網(wǎng)上找可以找到解決辦法】