非矩阵数据类型的C#和MATLAB互操作性

我正在编写一个需要调用MATLAB处理例程的C#程序。 我一直在研究MATLAB的COM接口。 不幸的是,就可以交换的数据类型而言,COM接口似乎相当有限。 支持矩阵和字符数组,但似乎不支持使用COM接口在C#和MATLAB之间交换结构数据或单元数组。 例如,在下面的代码中(假设在相应的文件夹中存在名为IM000000的DICOM图像),MATLAB变量’img’和’header’分别是256×256 int16矩阵和struct。 GetWorkspaceData调用适用于’img’,但对’header’返回null,因为’header’是一个结构。

public class MatlabDataBridge { MLApp.MLAppClass matlab; public MatlabDataBridge() { matlab = new MLApp.MLAppClass(); } public void ExchangeData() { matlab.Execute(@"cd 'F:\Research Data\'"); matlab.Execute(@"img = dicomread('IM000000');"); matlab.Execute(@"header = dicominfo('IM000000');"); matlab.GetWorkspaceData(@"img", "base", out theImg); // correctly returns a 2D array matlab.GetWorkspaceData(@"header", "base", out theHeader); // fails, theHeader is still null } } 

是否有合适的解决方法使用COM接口将结构数据编组到MATLAB中/从MATLAB编组? 如果没有,MATLAB Builder NE插件是否能很好地支持这一function?

我最终使用MATLAB Builder NE插件来解决问题。 代码最终看起来像这样:

 using MathWorks.MATLAB.NET.Arrays; using MathWorks.MATLAB.NET.Utility; using MyCompiledMatlabPackage; // wrapper class named MyMatlabWrapper is here ... matlab = new MyMatlabWrapper(); MWStructArray foo = new MWStructArray(1, 1, new string[] { "field1", "field2" }); foo["field1", 1] = "some data"; foo["field2", 1] = 5.7389; MWCellArray bar = new MWCellArray(1, 3); bar[1, 1] = foo; bar[1, 2] = "The quick brown fox jumped over the lazy dog."; bar[1, 3] = 7.9; MWArray result[]; result = matlab.MyFunction(foo, bar); // Test the result to figure out what kind of data it is and then cast // it to the appropriate MWArray subclass to extract and use the data 

考虑一下LabSharp (围绕Matlab引擎API的包装)。 然后你可以像这样交换结构:

 var engine = Engine.Open(false); var array = MxArray.CreateStruct(); array.SetField("MyField1", "toto"); array.SetField("MyField2", 12.67); engine.SetVariable("val", array); 

注意:这个LGPL包装器不是我的,请查看其API以获取更多详细信息。