实例说明
在本实例中,我们制作一个能够与Matlab进行交互的应用程序。程序运行结果如图78-1所示。
图78-1 运行结果
技术要点
l 引用Matlab库
l 执行Matlab命令
l 结束Matlab
实现过程
■ 新建项目
打开Visual Studio.NET,选择"新建项目",在项目类型窗口中选择"Visual Basic项目",在模板窗口中选择"Windows应用程序",在名称域中输入"CnMatlab",然后选择保存路径。单击"确认"。
■ 添加控件
向当前窗体添加五个Button按钮,两个Picture控件,一个Label控件,一个Hscroll控件和一个Vscroll控件。单击菜单"项目|添加引用",选中"Matlab Automation(Version5.3)Type Library"这一项。
注意:本程序只能在安装有Matlab的机器上运行。
■ 设置属性
将Label控件和Command按钮的Text属性设置为与界面一致。在此不再赘述。
Dim str1 As String
' 显示正弦图
Private Sub Command1_Click(ByVal eventSender As System.Object,ByVal eventArgs As System.EventArgs) Handles Command1.Click
Dim matlab As Object
matlab = CreateObject("matlab.application")
matlab.MinimizeCommandWindow()
str1 = "t=1:0.1:2*pi;y=sin(t);plot(t,y)"
matlab.Execute(str1)
matlab.Execute("print( gcf,'-djpeg','c:/foo')")
matlab.Quit()
matlab = Nothing
ShowPic()
End Sub
' 显示三维扇形图
Private Sub Command2_Click(ByVal eventSender As System.Object,ByVal eventArgs As System.EventArgs) Handles Command2.Click
Dim matlab As Object
matlab = CreateObject("matlab.application")
str1 = "sale=[100 150 400 250];pie3(sale,[0 0 1 0],{'春季','夏季','秋季','冬季'})"
matlab.Execute(str1)
matlab.Execute("print( gcf,'c:/foo')")
matlab.Quit()
matlab = Nothing
ShowPic()
End Sub
' 显示三维螺旋线图
Private Sub Command3_Click(ByVal eventSender As System.Object,ByVal eventArgs As System.EventArgs) Handles Command3.Click
Dim matlab As Object
matlab = CreateObject("matlab.application")
str1 = "t=0:0.1:8*pi;plot3(sin(t),cos(t),t)"
matlab.Execute(str1)
matlab.Execute("print( gcf,'c:/foo')")
matlab.Quit()
matlab = Nothing
ShowPic()
End Sub
' 显示立体球图
Private Sub Command4_Click(ByVal eventSender As System.Object,ByVal eventArgs As System.EventArgs) Handles Command4.Click
Dim matlab As Object
matlab = CreateObject("matlab.application")
str1 = "k = 5;n = 2^k-1;[x,y,z] = sphere(n);c = hadamard(2^k);surf(x,z,c);"
str1 = str1 & "colormap ([1 1 0; 0 1 1]);axis equal"
matlab.Execute(str1)
matlab.Quit()
matlab = Nothing
ShowPic()
End Sub
' 显示立体波浪图
Private Sub Command5_Click(ByVal eventSender As System.Object,ByVal eventArgs As System.EventArgs) Handles Command5.Click
Dim matlab As Object
matlab = CreateObject("matlab.application")
str1 = "[X,Y,Z] = peaks(30);surfc(X,Z);colormap hsv;axis ([-3 3 -3 3 -10 5])"
matlab.Execute(str1)
matlab.Execute("print( gcf,'c:/foo')")
matlab.Quit()
matlab = Nothing
ShowPic()
End Sub
■ 运行程序
单击菜单"调试|启动"或单击 图标运行程序。
小结
Matlab具有数值运算方便、快捷和画图的优点。它与VB结合,能实现功能强大的程序。因此,我们利用VB.NET可以开发出很有使用价值的程序。
原文链接:https://www.f2er.com/vb/264283.html