C # and MATLAB Compatibility for Non-Matrix Data Types

I am writing a C # program that should call MATLAB processing routines. I watched the MATLAB COM interface. Unfortunately, the COM interface seems rather limited in terms of the types of data that can be exchanged. Matrices and character arrays are supported, but there seems to be no support for exchanging structure or cell data between C # and MATLAB using the COM interface. For example, in the following code (provided that a DICOM image named IM000000 is present in the corresponding file folder), the variables "img" and "header" of MATLAB are an int16 256x256 matrix and a structure, respectively. Calling GetWorkspaceData works fine for 'img', but returns null for 'header' because 'header' is a structure.

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 } } 

Is there a suitable workaround for structuring structure data to / from MATLAB using the COM interface? If not, is this functionality well supported by MATLAB Builder NE?

+4
source share
2 answers

I decided to use the MATLAB Builder NE add-on to solve the problem. As a result, the code looks something like this:

 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 
+2
source

Take a look at LabSharp (a wrapper around the Matlab API). Then you can exchange the structure as follows:

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

NB: this LGPL cover is not mine, please check out its API for more details.

+1
source

Source: https://habr.com/ru/post/1342728/


All Articles