How to pass two multidimensional matrices from matlab to c #
I have a function written in matlab, for example Add / Subtract two matrices A and B (A and B are both 2-dimensional matrices):
function [X, Y] = add(A, B) X = A + B; Y = A - B;
I am 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 links 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 only get 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 the two outputs to two two dimensional floating point matrices in C #?
source to share
One of my friends found the answer and I decided to share it with others:
for example if we have this code in matlab to add / subtract 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 both two matrices and you can change these matrices of objects to the type you want (here for example double). This is where you can cast an object from 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();
source to share