C# Matlab 相互调用

来源:互联网 发布:nba全明星赛数据 编辑:程序博客网 时间:2024/04/30 06:46

C# Matlab 相互调用

测试环境

VisualStudio2013 / .net4.0
Matlab2015b

高版本的matlab对外接其它语言做得很方便了,并不需要一堆的配置。
其它语言与matlab的交互操作也类似。

C#调用Matlab

基本思路:将matlab函数打包成DLL文件,联合matlab数据支持DLL(MWArray.dll),交付给其它语言程序使用。

1、Matlab端的操作

编写matlab函数:

function [result,m,n] = GetSelfMultiplyResult(list)% 计算 矩阵与其转置矩阵的乘积% 测试返回多个结果result = list*list';[m,n] = size(result);end
function result = GetSelfSquareResult(list)% 计算 矩阵各元素平方后的结果result = list.^2;end

打包函数:

  1. 找到库编译器(LibraryCompiler)
    Matlab库编译器

  2. 打包函数
    如下图所示,
    1)选择目标类型(TYPE);
    2)添加需要打包的函数文件;
    3)重命名库名称。
    打包DLL库

  3. 重命名类名称,或者添加类,分配函数所属类。完成打包操作。
    打包类

导出DLL

在生成的文件中,找到“for_redistribution_files_only”文件夹,里面有
CalcMatResult.dll CalcMatResultNative.dll 两个dll文件,均可使用。
另外,MWArray.dll 在matlab安装目录中,参考路径:

X:\Program Files\MATLAB\R2015b\toolbox\dotnetbuilder\bin\win64\v2.0\

也可以直接使用Everything等软件直接搜索。

2、C#端的操作

C#端用到的就是 MWArray.dll 和 CalcMatResultNative.dll 这两个DLL文件。

  1. 添加DLL引用
    添加DLL引用

  2. 演示代码

using System;using CalcMatResultNative; //添加引用using MathWorks.MATLAB.NET.Arrays; //添加引用namespace CsharpMatlabDemo{    class Program    {        static void Main(string[] args)        {            int[,] list ={{1},{2},{3},{4}}; //列向量            MWArray array = new MWNumericArray(list);            CalcMatResultNative.Multiply multi = new Multiply();            object resultObj = multi.GetSelfMultiplyResult(3, array);// 3 表示返回的结果数量,要小于等于matlab对应函数实际的返回值数量            object[] resultObjs = (object[]) resultObj;            double[,] calcResult = (double[,])resultObjs[0];            double[,] sizem = (double[,])resultObjs[1];            double[,] sizen = (double[,])resultObjs[2];            Console.ReadKey();        }    }}

Matlab调用C#

matlab调用C#更加简单,先将C#代码编译成dll库,matlab中直接引用即可调用。

如果失败,注意检查使用的.net版本是否过高,平台(x64/86)是否匹配等问题。
注意选择Release版本的DLL(C#的Bebug版本也可以引用,但C++的不行)。

1、C#端操作

代码

namespace MatlabInterface{    public class Dialog    {        public static bool ShowSelectMsg(string msg, string title)        {            DialogResult r = MessageBox.Show(msg, title, MessageBoxButtons.YesNo, MessageBoxIcon.Question);            return r == DialogResult.Yes;        }        public string Msg { get; set; }        public void ShowMsg()        {            MessageBox.Show(Msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);        }    }}

2、Matlab操作

% 调用C# dll% 引用绝对路径NET.addAssembly('R:\Users\GrassPhy\Desktop\MatlabCsharpDemo\MatlabInterface.dll');% 静态方法调用select = MatlabInterface.Dialog.ShowSelectMsg('请选择...','提示');if select    disp('yes');else    disp('no');end% 成员方法调用dialog = MatlabInterface.Dialog();dialog.Msg = '提示信息';dialog.ShowMsg();

参考:
C#中使用MATLAB

1 0
原创粉丝点击