跟上篇文章一樣,也是用引擎的方式,但配置方法還是很不一樣的。
配置環境: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,成功
&n