This example shows how to:
Use the MATLAB® Compiler SDK™ product to create a package that applies MATLAB optimization routines to objective functions implemented as Java® objects.
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.
Note:
For complete reference information about the |
Build and run the application.
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 fminsearch
documentation. The class, Optimizer,
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. These two
methods, doOptim
and displayObj
,
encapsulate MATLAB functions. The MATLAB code for these
two methods is in doOptim.m
and displayObj.m
,
which can be found in
.matlabroot
\toolbox\javabuilder\Examples\ObjectRefExample\ObjectRefDemoComp
If you have not already done so, copy the files for this example as follows:
Copy the following folder that ships with MATLAB to
your work folder: matlabroot
\toolbox\javabuilder\Examples\ObjectRefExample
At the MATLAB command prompt, cd
to
the new ObjectRefExample
subfolder in your work
folder.
If you have not already done so, set the environment variables that are required on a development machine. See Configure Your Java Environment.
Write the MATLAB code that you want to access. This
example uses doOptim.m
and displayObj.m
,
which are already in your work folder in ObjectRefExample\ObjectRefDemoComp
.
For reference, the code of doOptim.m
is displayed
here:
function [x,fval] = doOptim(h, x0) % FMINSEARCH can't operate directly on Java % objective functions, % so you must create an anonymous function with the correct % signature to wrap the Java object. % Here, we assume our object has a method evaluateFunction() % that takes an array of doubles and returns a double. % This could become an Interface, % and we could check that the object implements that Interface. mWrapper = @(x) h.evaluateFunction(x); % Compare two ways of evaluating the objective function % These eventually call the same Java method, and return the % same results. directEval = h.evaluateFunction(x0) wrapperEval = mWrapper(x0) [x,fval] = fminsearch(mWrapper,x0)
displayObj.m
is displayed here:function className = displayObj(h) h className = class(h) whos('h') methods(h)
Open the Library Compiler app.
Create a Java package using the Library Compiler app to build a Java class that wraps around your MATLAB code.
Use the following information as you work through this example in Compile Java Packages with Library Compiler App:
Project Name | OptimDemo |
Class Name | Optimizer |
File to compile | doOptim.m and displayObj.m |
Write source code for a class that implements an object
function to optimize. The sample application for this example is in ObjectRefExample\ObjectRefDemoJavaApp\BananaFunction.java
.
The program listing is shown here:
public class BananaFunction { public BananaFunction() {} public double evaluateFunction(double[] x) { /* Implements the Rosenbrock banana function described in * the FMINSEARCH documentation */ double term1 = 100*java.lang.Math.pow((x[1]-Math.pow(x[0],2.0)),2.0); double term2 = Math.pow((1-x[0]),2.0); return term1 + term2; } }
fminsearch
documentation.Write source code for an application that accesses the MATLAB functions.
The sample application for this example is in ObjectRefExample\ObjectRefDemoJavaApp\PerformOptim.java
.
The program listing is shown here:
/* Necessary package imports */ import com.mathworks.toolbox.javabuilder.*; import OptimDemo.*; /* * Demonstrates the use of the MWJavaObjectRef class * Takes initial point for optimization as two arguments: * PerformOptim -1.2 1.0 */ class PerformOptim { public static void main(String[] args) { Optimizer theOptimizer = null; /* Stores component instance */ MWJavaObjectRef origRef = null; /* Java object reference to be passed to component */ MWJavaObjectRef outputRef = null; /* Output data extracted from result */ MWNumericArray x0 = null; /* Initial point for optimization */ MWNumericArray x = null; /* Location of minimal value */ MWNumericArray fval = null; /* Minimal function value */ Object[] result = null; /* Stores the result */ try { /* If no input, exit */ if (args.length < 2) { System.out.println("Error: must input initial x0_1 and x0_2 position"); return; } /* Instantiate a new Java object */ /* This should only be done once per application instance */ theOptimizer = new Optimizer(); try { /* Initial point --- parse data from text fields */ double[] x0Data = new double[2]; x0Data[0] = Double.valueOf(args[0]).doubleValue(); x0Data[1] = Double.valueOf(args[1]).doubleValue(); x0 = new MWNumericArray(x0Data, MWClassID.DOUBLE); System.out.println("Using x0 ="); System.out.println(x0); /* Create object reference to objective function object */ BananaFunction objectiveFunction = new BananaFunction(); origRef = new MWJavaObjectRef(objectiveFunction); /* Pass Java object to a MATLAB function that lists its methods, etc */ System.out.println("*********************************"); System.out.println("** Properties of Java object **"); System.out.println("*********************************"); result = theOptimizer.displayObj(1, origRef); MWArray.disposeArray(result); System.out.println("** Finished DISPLAYOBJ **********"); /* Call the Java component to optimize the function */ /* using the MATLAB function FMINSEARCH */ System.out.println("**********************************"); System.out.println("** Unconstrained nonlinear optim**"); System.out.println("**********************************"); result = theOptimizer.doOptim(2, origRef, x0); try { System.out.println("** Finished DOOPTIM ****** *********"); x = (MWNumericArray)result[0]; fval = (MWNumericArray)result[1]; /* Display the results of the optimization */ System.out.println("Location of minimum: "); System.out.println(x); System.out.println("Function value at minimum: "); System.out.println(fval.toString()); } finally { MWArray.disposeArray(result); } } finally { /* Free native resources */ MWArray.disposeArray(origRef); MWArray.disposeArray(outputRef); MWArray.disposeArray(x0); } } catch (Exception e) { System.out.println("Exception: " + e.toString()); } finally { /* Free native resources */ if (theOptimizer != null) theOptimizer.dispose(); } } }
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
Compile the PerformOptim.java
application
and BananaFunction.java
helper class using javac
.
When entering this command, ensure there are no spaces between path
names in the
argument.
For example, there should be no space between matlabroot
javabuilder.jar;
and .\distrib\OptimDemo.jar
in
the following example.
Open a Command Prompt window and cd
to
the
folder. matlabroot
\ObjectRefExample
Compile the application according to which operating system you are running on:
On Windows®, execute this command:
javac -classpath .;matlabroot\toolbox\javabuilder\jar\javabuilder.jar; .\distrib\OptimDemo.jar BananaFunction.java javac -classpath .;matlabroot\toolbox\javabuilder\jar\javabuilder.jar; .\distrib\OptimDemo.jar PerformOptim.java
On UNIX®, execute this command:
javac -classpath .:matlabroot/toolbox/javabuilder/jar/javabuilder.jar: ./distrib/OptimDemo.jar BananaFunction.java javac -classpath .:matlabroot/toolbox/javabuilder/jar/javabuilder.jar: ./distrib/OptimDemo.jar PerformOptim.java
Execute the PerformOptim
class file
as follows:
On Windows, type:
java -classpath .;matlabroot\toolbox\javabuilder\jar\javabuilder.jar .\distrib\OptimDemo.jar PerformOptim -1.2 1.0
On UNIX, type:
java -classpath .:matlabroot/toolbox/javabuilder/jar/javabuilder.jar: ./distrib/OptimDemo.jar PerformOptim -1.2 1.0
Note: You should be using the same version of Java that ships with MATLAB. To find out what version of Java MATLAB is running, enter the following MATLAB command: version -java
|
Note:
If you are running on the Mac 64-bit platform, you must add
the |
When run successfully, the PerformOptim
program
should display 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