Extract MATLABArray data return from Matlab dll in c# with new DATA API for dotnet

6 次查看(过去 30 天)
Built a Matlab dll, a struct is returned from some calcuation of a matlab function.
In the old MWArray data API, I can access the data by extract and marshal it to MWNumericArray.
In the new DATA API for DotNet, I can get the field of the struct data but it is in the {MathWorks.MATLAB.Types.MATLABArray}, how can I extract this array data in C#.
  5 个评论
Shaojun Xiao
Shaojun Xiao 2024-5-9
public static object GetMatlabStructArrayObject(MATLABArray analysisResults, int index = 0)
{
TMConvertBinder bindercdb = new TMConvertBinder(typeof(MATLABStruct[]), true);
var dataReadcdb = analysisResults.TryConvert(bindercdb, out var datacdb);
if (dataReadcdb == true)
{
var tt = datacdb as MATLABStruct[];
if (tt!=null && tt.Length > index)
{
return tt[index];
}
}
return null;
}

请先登录,再进行评论。

采纳的回答

Aditya Saikumar
Aditya Saikumar 2024-7-11
To extract data out of "MathWorks.MATLAB.Types.MATLABArray", you can simply typecast it to the datatype you want. If the conversion is not possible, you will get an error. Consider the following example of a function which returns a struct containing a double, a string and a struct array:
MATLAB Script:
function outputStruct = getData()
% This function returns a MATLAB struct 'outputStruct'
% Output:
% outputStruct - Struct containing a double field, a string
% and a struct array.
outputStruct = struct();
% Use arguments block to map a MATLAB type to a C# type
% Struct arrays in MATLAB map to a MATLAB Data Array
% MATLABStruct type in C#
arguments (Output)
outputStruct (1,1) struct
end
% fields
outputStruct.a = 1;
outputStruct.b = "hello";
% construct struct array
sArray = struct();
sArray.index = 1;
sArray.value = "one";
sArray(2).index = 2;
sArray(2).value = "two";
sArray(3).index = 3;
sArray(3).value = "three";
outputStruct.structArray = sArray;
end
C# code to extract data from the "getData()" result:
try
{
string ctfPath = @"GetData.ctf";
using (dynamic matlab = MATLABRuntime.StartMATLAB(ctfPath))
{
// call function
MATLABFunctions.getData(matlab, out MATLABStruct outputStruct);
// extract data
double a = (double)outputStruct.GetField("a");
string b = (string)outputStruct.GetField("b");
dynamic s = (MATLABStruct[])outputStruct.GetField("structArray");
// print the MATLABStruct elements
Console.WriteLine((string)s[1].value);
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
The following documentation link has an example of how to access MATLABStruct elements:
Hope this helps!

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Deploy to .NET Applications Using MWArray API 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by