当前位置:首页 > Windows程序 > 正文

[转载] C# matlab联合编程简介

2021-03-28 Windows程序

主要操作说明:

1. 找到matlab安装目录下的MCRInstaller.exe安装

MCRInstaller.exe 在安装目录下的 ..\MATLAB7\toolbox\compiler\deploy\win32\中;

2. 将写好的matlab的.m文件转换为动态链接库 2.1 编辑M文件

比如写了.m文件 f.m。其中的function C=f(A,B)实现的是C=A+B

function C=f(A,B)

C=A+B;

end

2.2 在matlab的命令窗口中输入deploytool

2.3 选择file-NewDeployment Project 2.4 选择MATLAVB Builder NE, .NET Component

然后OK

2.5 添加一个类

按‘添加类’,之后弹出对话框,输入类名,确认后,按‘添加m文件’,添加.m文件。

确认后。按”链接“。即可在matlab的工作目录中看到新建的对应这个工程名的文件夹,打开其中的distrib文件夹,可以看到f.ctf和f.dll两个文件,将这两个文件拷贝到c#工程的工作目录中。

3 C#中添加引用

在c#工程右侧的解决方案资源管理器中,鼠标右击“引用”,选择“添加引用”,,然后选择浏览,找到刚才放到C#工程中的.dll文件。选中确定。引用部分则会显示f。并且引用C:\Program Files\MATLAB\R2008a\toolbox\dotnetbuilder\bin\win32\v2.0中的MWArray.dll。然后引用中出线MWArray的引用。

在c#文件起始部位添加如下代码

using MathWorks.MATLAB.NET.Arrays;

using MathWorks.MATLAB.NET.Utility;

using f;

 

4 数据格式转换与使用 4.1 数据格式转换

fclass mfuntion = newfclass();

double[]a={1,2,3,4,5,6};

double[]b={2,4,6,8,10,12};

double[,] c;

MWNumericArray mA = newMWNumericArray(3, 2, a);            MWNumericArray mB = newMWNumericArray(3, 2, b);

MWNumericArray mC=(MWNumericArray)mfuntion.f(mA, mB);            c=(double[,])mC.ToArray(MWArrayComponent.Real);

4.2 为按钮click事件添加完整的代码

fclass mfuntion = new fclass();

double[] a = { 1, 2, 3, 4, 5, 6 };

double[] b = { 2, 4, 6, 8, 10, 12 };

double[,] c;

MWNumericArray mA = new MWNumericArray(3, 2, a);

MWNumericArray mB = new MWNumericArray(3, 2, b);

MWNumericArray mC = (MWNumericArray)mfuntion.f(mA, mB);

c = (double[,])mC.ToArray(MWArrayComponent.Real);

int row = c.GetLength(0);

int col = c.GetLength(1);

string text = "\r\n";

for (int i = 0; i < row; i++)

{

for (int j = 0; j < col; j++)

text += Convert.ToString(c[i, j]) + ‘ ‘;

text += "\r\n";

}

textBox1.Text = text;

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/69104.html