一、简介
使用C#调用matlab程序完成两个数求和的功能,将求和结果显示在文本框。
二、matlab编程与封装
(1)编写matlab程序(add.m),如下:
function res = add(x,y)
res = x+y;
end
(2)在命令行输入命令:deploytool,在弹出的界面选择library complier
(3)添加需要封装的add.m文件,并且将类的名字改为MyAddClass,其他的设置如下图,最后点击Package
打包之后生成的文件如下图所示:
二、C#编程
(1)新建c#窗体工程,把打包文件中的for_Testing中的add.dll放进C#工程目录下,MWArray.dll(用于C#和matlab的数据传送)复制出来放到C#工程目录下,MWArray.dll在安装目录\toolbox\dotnetbuilder\bin\win64\v4.0 中,我电脑的位置如下图,我这里直接复制出来放到C#工程目录下。
(2)添加对add.dll和MWArray.dll的引用
using MathWorks.MATLAB.NET.Arrays;
using add;
(3)编写完整C#代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MathWorks.MATLAB.NET.Arrays;
using add;
namespace demo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MWArray add_x = (MWArray)15;//c#和matlab的数据传送必须用MWArray类型
MWArray add_y = (MWArray)10;
MyAddClass temp_obj = new MyAddClass();
string str = temp_obj.add(add_x, add_y).ToString();
label1.Text = str;
}
}
}
(4)运行结果如下: