跟上篇文章一样,也是用引擎的方式,但配置方法还是很不一样的。
配置环境:vs2013(64位)+Matlab2013a(64位)+win8.1(64位)
以Matlab安装路径:C:\Program Files\MATLAB\R2013a为例
1.添加引用:
一个是添加MWArray.dll的引用,路径为:C:\Program Files\MATLAB\R2013a\toolbox\dotnetbuilder\bin\win64\v2.0,
另一个是添加Matlab类型库的引用。在“引用”上右击“添加引用”,如下图
2.加入命名空间:
using MathWorks;
using MathWorks.MATLAB;
using MathWorks.MATLAB.NET.Arrays;
using MathWorks.MATLAB.NET.Utility;
using MLApp;
3.示例代码:
一共尝试了四种方式,其中两种成功,两种失败,具体代码如下(加入到button事件里):
////////////////////引擎方式1,失败
MLApp.MLAppClass matlab = new MLApp.MLAppClass();
string command;
command = "t=2:0.2:4*pi;y=sin(t);plot(t,y)";
matlab.Visible = 1;
matlab.Execute(command);
command = @"print(gcf, '-djpeg', 'c:\Test1')";
matlab.Execute(command);
pictureBox1.Image = Image.FromFile(@"c:\Test1.jpg");
////////////////////引擎方式2,失败
MLApp.DIMLApp matlab = null;
Type matlabAppType = System.Type.GetTypeFromProgID("Matlab.Application");
matlab = System.Activator.CreateInstance(matlabAppType) as MLApp.DIMLApp;
string command;
command = "t=2:0.2:4*pi;y=sin(t);plot(t,y)";
matlab.Visible = 1;
matlab.Execute(command);
command = @"print(gcf, '-djpeg', 'c:\Test1')";
matlab.Execute(command);
pictureBox1.Image = Image.FromFile(@"c:\Test1.jpg");
////////////////////引擎方式3,成功
MLApp.MLApp matlab = null;
Type matlabAppType = System.Type.GetTypeFromProgID("Matlab.Application");
matlab = System.Activator.CreateInstance(matlabAppType) as MLApp.MLApp;
string command;
command = "t=2:0.2:4*pi;y=sin(t);h = plot(t,y)";
String path = Directory.GetCurrentDirectory();//获取当前路径
matlab.Visible = 0;
matlab.Execute(command);
command = @"print(gcf, '-djpeg', '" + path + "\\Test1');close all";
matlab.Execute(command);
pictureBox1.Image = Image.FromFile(path + "\\Test1.jpg");
////////////////////引擎方式4,成功
MLApp.MLApp O_matlab = new MLApp.MLApp();
O_matlab.Visible = 0;
string command1, command2;
command1 = "t=0:0.01:2*pi;y=sin(t);h=plot(t,y)";//matlab脚本命令行
String path = Directory.GetCurrentDirectory();//获取当前路径
command2 = @"print(gcf, '-djpeg', '" + path + "\\Test1');close all";
O_matlab.Execute(command1);
O_matlab.Execute(command2); // 执行Matlab命令
O_matlab.Quit();
O_matlab = null;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Image = Image.FromFile(path + "\\Test1.jpg"); //读取图像
得到结果如下图:
转自:http://blog.sina.com.cn/s/blog_6f7265cf0101nqhw.html