参考:http://www.cnblogs.com/eniac12/p/4390845.html
C#版本:VS2015 matlab版本:matlab2015a
使用版本不一样,精简了上文中的主要程序:
MatrixOpera.m
%-------------------------------------------------------- function [addRlt,minusRlt]=MatrixOpera(a,b) % 矩阵相加,相减 [m1,n1]=size(a); [m2,n2]=size(b); if m1~=m2 || n1~=n2 display('矩阵大小不相同') error('参数错误'); end addRlt=a+b; minusRlt=a-b; end %-----------------------------------------------------------
C#调用过程
matPrj test = new matPrj(); //将myMathClass类实例化 Array a = new double[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };//定义两个输入参数 Array b = new double[,] { { 1, 1 }, { 1, 1 }, { 1, 1 } }; Array c = new double[3, 2];//定义C#中接收输出参数的类型 Array d = new double[3, 2]; //输入参数成功转化为两个MWArray元素类型 MWArray matlab_a = (MWNumericArray)a; MWArray matlab_b = (MWNumericArray)b; //此例实现了两个三行两列的矩阵相加减 MWArray[] agrsOut = test.MatrixOpera(2, matlab_a, matlab_b); //转化为二维数组 c = agrsOut[0].ToArray(); d = agrsOut[1].ToArray(); //一定要注意最后接收参数的转化,不同类型的接收参数用的转换函数不同 //二维数组用ToArray()函数转换 //一维数组用ToVector(MWArrayComponent.Real)函数转换 //单个double值用ToScalarDouble()函数转换 //单个int值用ToScalarInteger()函数转换 for (int i = 0; i <= 2; i++)//输出结果验证 { for (int j = 0; j <= 1; j++) { textBox1.Text += c.GetValue(i, j).ToString() + " "; textBox2.Text += d.GetValue(i, j).ToString() + " "; } textBox1.Text += " ";//换行 textBox2.Text += " "; } }
参考:http://cn.mathworks.com/help/compiler_sdk/dotnet/integrate-your-net-assembly-into-a-c-application.html?searchHighlight=Call%20MATLAB%20method%20compiled%20to%20.NET%20assembly