フィルターのクリア

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

10 ビュー (過去 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 月 8 日
Still unable to convert an array of user defined STRUCT back by the customer marshalling.
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 Center および File ExchangeDeploy 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