假设随便一个简单的函数叫做matlab_eigen.cpp,它用到第三方库(matlab eigen函数),内容如下:
[cpp] view plain copy /* * matlab_eigen.cpp * * This is an example of how to create a surface contour plot in MATLAB * http://cn.mathworks.com/matlabcentral/fileexchange/35311-matlab-plot-gallery-surface-contour-plot/content/html/Surface_Contour_Plot.html */ #include <iostream> #include <math.h> #include "engine.h" int main() { Engine *ep; //定义Matlab引擎指针。 if (!(ep=engOpen("\0"))) //测试是否启动Matlab引擎成功。 { std::cout<< "Can't start MATLAB engine"<<std::endl; return EXIT_FAILURE; } // 向matlab发送命令。在matlab内部自己去产生即将绘制的曲线上的数据。 // Create a grid of x and y data engEvalString(ep, "y = -10:0.5:10;x = -10:0.5:10; [X, Y] = meshgrid(x, y);"); // Create the function values for Z = f(X,Y) engEvalString(ep, "Z = sin(sqrt(X.^2+Y.^2)) ./ sqrt(X.^2+Y.^2);"); // Create a surface contour plor using the surfc function, Adjust the view angle engEvalString(ep, "figure;surfc(X, Y, Z); view(-38, 18);"); // Add title and axis labels engEvalString(ep, "title('Normal Response');xlabel('x');ylabel('y');zlabel('z')"); //Use cin.get() to make sure that we pause long enough to be able to see the plot. std::cout<<"Hit any key to exit!"<<std::endl; std::cin.get(); return EXIT_SUCCESS; }
用方法一编译: $ g++ matlab_eigen.cpp -o matlab_eigen -I/opt/MATLAB/R2012a/extern/include -L/opt/MATLAB/R2012a/bin/glnxa64 -leng -lmx 用方法二编译: 设置环境变量: MATLAB=/opt/MATLAB/R2012a export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$MATLAB/bin/glnxa64 export LIBRARY_PATH=$LIBRARY_PATH:$MATLAB/bin/glnxa64 export CPLUS_INCLUDE_PATH=CPLUS_INCLUDE_PATH:$MATLAB/extern/include 编译:
$ g++ matlab_eigen.cpp -o matlab_eigen -leng -lmx
运行及结果:(如果你编译过程遇到错误可以参考我这篇文章。) ./matlab_eigenHit any key to exit!
参考: http://walkerqt.blog.51cto.com/1310630/1300119 http://stackoverflow.com/questions/4250624/ld-library-path-vs-library-path http://blog.chinaunix.NET/uid-26980210-id-3365027.html