如何将两个多维矩阵从matlab传递到C#

时间:2015-05-27 04:29:48

标签: c# matlab visual-studio matrix

我有一个用matlab编写的函数,例如添加/减去两个矩阵A和B(A和B都是二维矩阵):

function [X, Y] = add(A, B) 
X = A + B;
Y = A - B;

我在C#工作,我想从visual studio调用此函数,并在C#中使用此函数的输出。所以我将MLApp.dll添加到我的引用和

MLApp.MLApp matlab = new MLApp.MLApp();
matlab.Execute(@"cd D:\Matlab");
object result = null;
matlab.Feval("add", 2, out result, Mymat1, Mymat2); //Mymat1/2 are my matrices passing to matlab

1)但是在这段代码中,我只能得到一个输出而且我不知道如何获得它们两个因为Feval有一个输出参数?
 2)那么如何在C#中将两个输出转换为两个二维浮点矩阵?

1 个答案:

答案 0 :(得分:0)

我的一位朋友找到了答案,我决定与其他人分享:

例如,如果我们在matlab中使用此代码来添加/减去两个矩阵:

function [add, sub] = myFunc(a,b,c, par1, par2) 
add = par1 + par2;
sub = par1 - par2;

然后我们可以从visual studio中调用它 你可以访问两个矩阵 并且您可以将这些对象矩阵更改为您想要的类型(这里例如double)在这里您可以从对象转换为您喜欢的类型

        // Create the MATLAB instance 
        MLApp.MLApp matlab = new MLApp.MLApp();

        // Change to the directory where the function is located 
        matlab.Execute(@"cd C:\matlabInC");

        // Define the output 
        object result = null;

        // creat two array
        double[,] par1 = new double[3, 3];
        double[,] par2 = new double[3, 3];

        //Give value to them.....


        // Call the MATLAB function myfunc
        matlab.Feval("myFunc", 2, out result, 3.14, 42.0, "world", par1, par2);

        // Display result 
        object[] res = result as object[];


        object arr = res[0];
        Console.WriteLine(arr.GetType());
        // addition resualt
        double[,] da = (double[,])arr;

        //Show Result of Addition.....
        for (int i = 0; i < da.GetLength(0); i++)
        {
            for (int j = 0; j < da.GetLength(1); j++)
            {
                Console.WriteLine("add[" + i + "," + j + "]= " + da[i, j] + ", ");
            }
        }

        // subtraction resualt
        arr = res[1];
        double[,] da2 = (double[,])arr;

        //Show subtraction result...
        for (int i = 0; i < da2.GetLength(0); i++)
        {
            for (int j = 0; j < da2.GetLength(1); j++)
            {
                Console.WriteLine("sub[" + i + "," + j + "]= " + da2[i, j] + ", ");
            }
        }

        Console.ReadLine();