MATLAB Answers

Example of coding a `struct` in Java when packaging Matlab function?

조회 수: 2(최근 30일)
FM
FM 2020년 10월 19일
댓글: FM 2020년 10월 29일
I am embarking on writing a Java wrapper for intlinprog, and learning Java at the same time. My OOP experience is C++ circa 2004, so it has been an interesting learning curve reading up on Java code idioms, patterns, Matlab data conversions, the packaging process itself, and the Java compilation/invocation.
intlinprog takes a struct argument named options. Is there an example of how to code up a MATLAB struct in Java? According to Rules for Data Conversion Between Java and MATLAB, "Structure arrays are constructed and accessed as arrays of MWArray". Most examples of Java/Matlab interoperation use classes derived from MWArray.
I am using Matlab Compiler SDK rather than the Matlab engine, so I assume that Java class com.mathworks.matlab.types.Struct does not apply. I welcome any corrections if I'm wrong.

채택된 답변

Todd Flanagan
Todd Flanagan 2020년 10월 29일
편집: Todd Flanagan 2020년 10월 29일
The eaiest way to learn how to create structs in the Java API is to add a sample in the Library Compiler tool with a sample struct and sample data. This will generate Java code that will show you how to use the struct api with your own data.
Here is an example:
a.i1 = 1.0
a.i2 = 'a string'
foo(a)
And the generated Java method:
public static void fooExample() {
MWStructArray aIn = null;
MWArray aIn_i1_1 = null;
MWArray aIn_i2_1 = null;
Object[] results = null;
try {
// instantiate data within struct aIn
double aIn_i1_1Data = 1.0;
aIn_i1_1 = new MWNumericArray(aIn_i1_1Data, MWClassID.DOUBLE);
String aIn_i2_1Data = "a string";
aIn_i2_1 = new MWCharArray(aIn_i2_1Data);
// instantiate struct aIn and set inner data
int[] aInDims = {1, 1};
String[] aInFields = {"i1", "i2"};
aIn = new MWStructArray(aInDims, aInFields);
aIn.set("i1", 1, aIn_i1_1);
aIn.set("i2", 1, aIn_i2_1);
results = class1Instance.foo(aIn);
} catch (Exception e) {
e.printStackTrace();
} finally {
// Dispose of native resources
MWArray.disposeArray(aIn);
MWArray.disposeArray(aIn_i1_1);
MWArray.disposeArray(aIn_i2_1);
MWArray.disposeArray(results);
}
}

추가 답변(0개)

Community Treasure Hunt

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

Start Hunting!

Translated by