配置:
(1)Microsoft Visual Studio 2005
(2)Matlab R2008a
第一步:
首先安裝Matlab;
安裝Visual Studio 2005或者更高版本;
安裝MCRInstall.exe,我安裝完Matlab之后在這里找得的:E:\installed\matlab\toolbox\compiler\deploy\win32
點(diǎn)擊:我的電腦-屬性-高級(jí)-環(huán)境變量-系統(tǒng)變量-PATH-編輯,在變量值輸入框中,不要?jiǎng)h除以前的字符串,在最前面加入MCR的安裝路徑,如:E:\installed\matlab\v78\bin\win32; 然后確定、保存、重啟電腦。(我就是不知道需要這兩步,老是在C#創(chuàng)建Matlab的訪問對象時(shí),出現(xiàn):“xxx的類型初始值設(shè)定項(xiàng)引發(fā)異常?!?,完全不理解是什么原因,被耽擱了大量時(shí)間,直到安裝了Matlab 2008a,仔細(xì)閱讀它生成的readme.txt才知道)
第二步: 在matlab的Command window中輸入mbuild -setup顯示如下
>> mbuild -setup
Please choose your compiler for building standalone MATLAB applications: Would you like mbuild to locate installed compilers [y]/n? n %選擇n
Select a compiler:
[1] Lcc-win32 C 2.4.1
[2] Microsoft Visual C++ 6.0
[3] Microsoft Visual C++ .NET 2003
[4] Microsoft Visual C++ 2005
[5] Microsoft Visual C++ 2005 Express Edition
[6] Microsoft Visual C++ 2008
[0] None Compiler: 4 %選擇4,其他編譯器可以選相應(yīng)的選項(xiàng),我沒有驗(yàn)證過
Please verify your choices: Compiler: Microsoft Visual C++ 2005 Location: D:Program FilesMicrosoft Visual Studio 8.0 Are these correct [y]/n? y %看上述信息,如果正確選擇y
第三步: 編寫m文件:
function test(h,D)
for x=-10:0.1:10
if x>D
y=h;
hold on;
plot(x,y)
else if x<-D
y=-h;
hold on;
plot(x,y)
else
y=h/(D*x);
hold on;
plot(x,y)
end
end
end
第四步:建立項(xiàng)目:
在matlab中點(diǎn)擊“File- new -Development Project” 自己選擇項(xiàng)目保存目錄和項(xiàng)目名,如Test.prj 類型選擇.NET Component,如果你要生成更通用的COM組件,選擇Generic COM Component。添加剛才的m文件到這個(gè)新建的項(xiàng)目中去。點(diǎn)擊Build the project按鈕(這個(gè)按鈕的圖標(biāo)和微軟開發(fā)工具的Build圖標(biāo)一樣)或者右擊選擇“build”,等待3,4分鐘。建立成功。
第五步: 打開2005.新建控制臺(tái)應(yīng)用程序.添加引用.選擇瀏覽,選擇剛才用Deployment新建的項(xiàng)目的Test目錄的Test.dll文件.再選擇E:\installed\matlab\toolbox\dotnetbuilder\bin\win32\v2.0目錄下的MWArray.dll文件。
Program.cs中代碼如下:
using System;
using System.Collections.Generic;
using System.Text;
using MathWorks.MATLAB.NET.Arrays;
using MathWorks.MATLAB.NET.Utility;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Test.Test ts = new Test.Test();
MathWorks.MATLAB.NET.Arrays.MWArray m, n;
m = 4; n = 5;
ts.test((MWNumericArray)m, (MWNumericArray)n);
Console.ReadKey();
}
}
}
即可調(diào)用matlab繪出圖形。