简体   繁体   中英

How pass two multi-dimensional matrices from matlab to C#

I have a function written in matlab, for example Adding/Subtracting two matrices A and B(A and B both are two dimensional matrices):

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

I'm working in C# and I want to call this function from visual studio and use the outputs of this function in C#. so I added MLApp.dll to my references and

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) but in this code I can get only one output and I don't know how to get both of them because Feval has one out parameter?
2) then how can I cast two outputs to two two-dimensional float matrices in C#?

One of my friends find the answer and I decided to share it with others :

for example if we have this code in matlab for adding/subtracting two matrices:

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

then we can call it from visual studio and you can access two both of matrices and you can change these object matrices to type that you want(here for example double) Here you can cast from object to your favorite type

        // 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(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM