Using MATLAB Handle Objects in Java
MATLAB Handle Objects
MATLAB® handle objects are instances of the handle
class. Accessing MATLAB handle
objects enables you to set the values of public properties on those
objects. For example, all MATLAB graphics and user interface
objects are handle objects.
Java HandleObject
Class
Use the com.mathworks.matlab.types.HandleObject
class
to represent handle objects returned from MATLAB to Java®.
You can pass the HandleObject
instance only to
the MATLAB session in which it was created. You cannot construct
a HandleObject
in Java.
Set Graphics Object Properties from Java
The MATLAB plot
function
returns the handle objects referencing the lines in the graph. Use
these handles with the set
function
to modify the appearance of the graph by changing the properties of
the lines.
This example executes the following function calls in MATLAB:
% Create a 2-by-3 array of doubles data = [1,2,3;-1,-2,-3]; % Plot the data and return the line handles h = plot(data); % Set the line width to 2 points set(h,'LineWidth',2); % Pause for 5 seconds, just to see the result pause(5)
The Java code uses these steps to cause the execution of the MATLAB code as described:
Create a 2D
double
array calleddata
.Cast the
data
array to anObject
so MATLAB interprets the array as one argument toplot
.Return
HandleObject
arrayh
from MATLAB with the line handles.Call the MATLAB
set
function to set theLineWidth
property of the line handles to 2.0. Convert the name of theLineWidth
property from aString
to achar[]
because theset
function requires property names to be MATLABchar
arrays.Pause for
5
seconds and then close the MATLAB engine.
import com.mathworks.engine.*; import com.mathworks.matlab.types.*; public class PassHandleObject { public static void main(String[] args) throws Exception { MatlabEngine eng = MatlabEngine.startMatlab(); double[][] data = {{1.0, 2.0, 3.0}, {-1.0, -2.0, -3.0}}; HandleObject[] h = eng.feval("plot", (Object) data); String lw = ("LineWidth"); eng.feval(0, "set", h, lw.toCharArray(), 2.0); eng.eval("pause(5)"); eng.close(); } }