这几天正在搞FEM,想到了matlab的矩阵处理颇为方便,于是想到能不能结合c#写个简单fem程序,用c#开发图形界面,计算部分由matlab的的dll(用deploytool编译成.net assembly)提供。
环境如下:
matlab2012
vs2005(对应net framwork 2.0)
注意:
1.安装vs2005时要选择x64编译环境,否则在matlab中 “mex -setup” 时会出错
2..在matlab建立deploytool工程时,要选择2.0的 .net famework,否则导入dll时出错)
步骤1:
matlab中
》mbuild -setup
选择 vs2005 并设置相应vs2005的路径
步骤2:
安装mcr(会自动添加其路径到path中)
D:\MATLAB2012\R2012b\toolbox\compiler\deploy\win64
步骤3:
建立.m文件
function b=myinv(a)
b=inv(a)
》deploytool
选择.net assembly类型,点击build
步骤4:
建立c#项目,添加引用TestInv.dll
program.cs中代码如下:
using System;
using System.Collections.Generic;
using System.Text;
using MathWorks.MATLAB.NET.Utility;
using MathWorks.MATLAB.NET.Arrays;
using TestInv;
namespace TestNetMagic
{
class Program
{
#region MAIN
[STAThread]
static void Main(string[] args)
{
int arraySize;
double[,] input=new double[,]{{1,2},{3,4}};
MWNumericArray xx = new MWNumericArray(MWArrayComplexity.Real, 2, 2); //输入参数,2*2矩阵
xx[1,1] = 1;
xx[1,2] = 2;
xx[2,1] = 3;
xx[2,2] = 4;
double inp = 9;
// System.Array myinp = (System.Array)input;
// MWNumericArray x = MWNumericArray.MakeSparse(1, 1, MWArrayComplexity.Real, (1 * 1));//new MWNumericArray(MWArrayComplexity.Real, MWNumericType.Double, M, N);
//MATLAB.NET.Arrays.MWNumericArray.MakeSparse(2,2,MathWorks.MATLAB.NET.Arrays.MWArrayComplexity.Real, 2);
// new MWNumericArray(MWArrayComplexity.Real, MWNumericType.Double, 2, 2);
//new MWNumericArray(MWArrayComplexity.Real, 2, 2);
// x[1] = 1;
// MagicSquareClass magic = null;
TestInv.TestInv inv = null;
try
{
arraySize = (0 != args.Length) ? Int32.Parse(args[0]) : 4;
inv = new TestInv.TestInv();
MWArray nativeArray = null;
nativeArray=inv.myinv(xx);
System.Array myArray=nativeArray.ToArray(); //返回值
for (int i = myArray.GetLowerBound(0); i <= (int)myArray.GetUpperBound(0); i++)
for (int j = myArray.GetLowerBound(1); j <= (int)myArray.GetUpperBound(1); j++)
Console.WriteLine("Element({0},{1})= {2}", i, j, myArray.GetValue(i, j));
Console.ReadLine(); // Wait for user to exit application
}
catch (System.Runtime.InteropServices.COMException exception)
{
Console.WriteLine("COM Error: {0}", exception);
}
catch (Exception exception)
{
Console.WriteLine("Error: {0}", exception);
}
finally
{
if(inv != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(inv);
}
}
#endregion
}
}
最后输出逆矩阵: