码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2015-07-30 00:17:33      阅读:366      评论:0      收藏:0      [点我收藏+]

标签:

                                                                                              原作者  文月

主要操作说明:

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;

 

 

5. 备注

更多的数据格式转换,请用matlabhelp索引MWArray。

比如,MWNumericArray的构造函数页。关键是构造函数实现了两种数据格式的转换。

 

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

标签:

原文地址:http://www.cnblogs.com/arxive/p/4687750.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!