分享

C#调用matlab函数

 伊本经阁 2012-05-08
C#调用matlab函数

配置:

(1)Microsoft Visual Studio 2005

(2)Matlab R2008a

第一步:

首先安装Matlab;

安装Visual Studio 2005或者更高版本;

安装MCRInstall.exe,我安装完Matlab之后在这里找得的:E:\installed\matlab\toolbox\compiler\deploy\win32

点击:我的电脑-属性-高级-环境变量-系统变量-PATH-编辑,在变量值输入框中,不要删除以前的字符串,在最前面加入MCR的安装路径,如:E:\installed\matlab\v78\bin\win32; 然后确定、保存、重启电脑。(我就是不知道需要这两步,老是在C#创建Matlab的访问对象时,出现:“xxx的类型初始值设定项引发异常。”,完全不理解是什么原因,被耽搁了大量时间,直到安装了Matlab 2008a,仔细阅读它生成的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,其他编译器可以选相应的选项,我没有验证过

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

第四步:建立项目:

在matlab中点击“File- new -Development Project” 自己选择项目保存目录和项目名,如Test.prj 类型选择.NET Component,如果你要生成更通用的COM组件,选择Generic COM Component。添加刚才的m文件到这个新建的项目中去。点击Build the project按钮(这个按钮的图标和微软开发工具的Build图标一样)或者右击选择“build”,等待3,4分钟。建立成功。

第五步: 打开2005.新建控制台应用程序.添加引用.选择浏览,选择刚才用Deployment新建的项目的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();

        }
    }
}

即可调用matlab绘出图形。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多