Main Content

Pass Java Objects to MATLAB

Overview

This example shows you how to create a Java® application that finds a local minimum of an objective function using the MATLAB® optimization function fminsearch and the MWJavaObjectRef class.

In this example, you perform the following steps:

  1. Use MATLAB Compiler SDK™ to create a package that applies MATLAB optimization routines to objective functions implemented as Java objects.

  2. Access the MATLAB functions in a Java application, including use of the MWJavaObjectRef class to create a reference to a Java object and pass it to the generated Java methods.

  3. Build and run the application.

OptimDemo Package

The OptimDemo package finds a local minimum of an objective function and returns the minimal location and value.

The package uses the MATLAB optimization function fminsearch, and this example optimizes the Rosenbrock banana function used in the MATLAB fminsearch documentation.

The Optimizer class performs an unconstrained nonlinear optimization on an objective function implemented as a Java object. A method of this class, doOptim, accepts an initial guess and Java object that implements the objective function, and returns the location and value of a local minimum. The second method, displayObj, is a debugging tool that lists the characteristics of a Java object.

The two methods, doOptim and displayObj, encapsulate MATLAB functions.

Files

MATLAB FunctionsdoOptim.m
displayObj.m
MATLAB Function Locationmatlabroot\toolbox\javabuilder\Examples\ObjectRefExample\ObjectRefDemoComp
Java Code Locationmatlabroot\toolbox\javabuilder\Examples\ObjectRefExample\ObjectRefDemoJavaApp
javabuilder.jarmatlabroot\toolbox\javabuilder\jar

Procedure

  1. Copy the ObjectRefExample folder that ships with MATLAB to your work folder:

    copyfile(fullfile(matlabroot,'toolbox','javabuilder','Examples','ObjectRefExample'),'ObjectRefExample')

    At the MATLAB command prompt, navigate to the new ObjectRefExample\ObjectRefDemoComp subfolder in your work folder.

  2. Examine the MATLAB code you want to access from Java. This example uses doOptim.m and displayObj.m.

    function [x,fval] = doOptim(h, x0)
    directEval = h.evaluateFunction(x0)
    wrapperEval = mWrapper(x0)
    [x,fval] = fminsearch(mWrapper,x0)
    function className = displayObj(h)
    h
    className = class(h)
    whos('h')
    methods(h)

  3. Build the Java package with the Library Compiler app or compiler.build.javaPackage using the following information:

    FieldValue
    Library NameOptimDemo
    Class NameOptimizer
    Files to CompiledoOptim.m
    displayObj.m

    For example, if you are using compiler.build.javaPackage, type:

    buildResults = compiler.build.javaPackage(["doOptim.m","displayObj.m"], ...
    'PackageName','OptimDemo', ...
    'ClassName','Optimizer');

    For more details, see the instructions in Generate Java Package and Build Java Application.

  4. Write source code for a class that implements an object function to optimize. The code for this example is in the file BananaFunction.java.

     BananaFunction.java

    The class implements the Rosenbrock banana function described in the MATLAB fminsearch documentation.

  5. Write source code for an application that accesses the MATLAB functions. The code for this example is in the file PerformOptim.java.

     PerformOptim.java

    The program does the following:

    • Instantiates an object of the BananaFunction class above to be optimized.

    • Creates an MWJavaObjectRef that references the BananaFunction object, as shown:

      origRef = new MWJavaObjectRef(objectiveFunction);
      .

    • Instantiates an Optimizer object.

    • Calls the displayObj method to verify that the Java object is being passed correctly.

    • Calls the doOptim method, which uses fminsearch to find a local minimum of the objective function.

    • Uses a try/catch block to handle exceptions.

    • Frees native resources using MWArray methods.

  6. In MATLAB, navigate to the ObjectRefDemoJavaApp folder.

  7. Copy the generated OptimDemo.jar package into this folder.

    • If you used compiler.build.javaPackage, type:

      copyfile(fullfile('..','ObjectRefDemoComp','OptimDemojavaPackage','OptimDemo.jar'))
    • If you used the Library Compiler, type:

      copyfile(fullfile('..','ObjectRefDemoComp','OptimDemo','for_testing','OptimDemo.jar'))
  8. Open a command prompt window and navigate to the ObjectRefDemoJavaApp folder where you copied OptimDemo.jar.

  9. Compile the PerformOptim.java application and BananaFunction.java helper class using javac.

    • Windows®

      To compile BananaFunction.java, type:

      javac -classpath "matlabroot\toolbox\javabuilder\jar\javabuilder.jar";.\OptimDemo.jar BananaFunction.java
      To compile PerformOptim.java, type:
      javac -classpath "matlabroot\toolbox\javabuilder\jar\javabuilder.jar";.\OptimDemo.jar PerformOptim.java

    • UNIX®

      To compile BananaFunction.java, type:

      javac -classpath "matlabroot/toolbox/javabuilder/jar/javabuilder.jar":./OptimDemo.jar BananaFunction.java
      To compile PerformOptim.java, type:
      javac -classpath "matlabroot/toolbox/javabuilder/jar/javabuilder.jar":./OptimDemo.jar PerformOptim.java

    Replace matlabroot with the path to your MATLAB or MATLAB Runtime installation folder. For example, on Windows, the path may be C:\Program Files\MATLAB\R2024b.

  10. Run the PerformOptim application.

    On Windows, type:

    java -classpath .;"matlabroot\toolbox\javabuilder\jar\javabuilder.jar";.\OptimDemo.jar PerformOptim -1.2 1.0

    On Linux®, type:

    java -classpath .:"matlabroot/toolbox/javabuilder/jar/javabuilder.jar":.\OptimDemo.jar PerformOptim -1.2 1.0

    Note

    If you are running the application on the Mac 64-bit platform, you must add the -d64 flag in the Java command.

The PerformOptim program displays the following output:

Using x0 =
-1.2000    1.0000
*****************************************************
** Properties of Java object                       **
*****************************************************
 
h =
 
BananaFunction@1766806
 
className =
 
BananaFunction
 
  Name      Size            Bytes  Class             Attributes
 
  h         1x1                    BananaFunction              
 
Methods for class BananaFunction:
 
 BananaFunction    getClass          notifyAll         
equals            hashCode          toString          
evaluateFunction  notify            wait              
 
** Finished DISPLAYOBJ ******************************
*****************************************************
** Performing unconstrained nonlinear optimization **
*****************************************************
 
directEval =
 
   24.2000
 
 wrapperEval =
 
   24.2000
 
 x =
 
    1.0000    1.0000
 
 fval =
 
   8.1777e-10
 
Optimization successful
** Finished DOOPTIM *********************************
Location of minimum: 
1.0000    1.0000
Function value at minimum: 
8.1777e-10

See Also

|

Related Topics