| Contents | Index |
| On this page… |
|---|
This example shows how to:
Use the MATLAB Builder JA product to create a component (OptimDemo) that applies MATLAB optimization routines to objective functions implemented as Java objects.
Access the component in a Java application (PerformOptim.java), including use of the MWJavaObjectRef class to create a reference to a Java object (BananaFunction.java) and pass it to the component.
Build and run the application.
The component OptimDemo finds a local minimum
of an objective function and returns the minimal location and value.
The component 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 Settings for Environment Variables (Development Machine).
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) %DOOPTIM Optimize a Java objective function % This file is used as an example for the % MATLAB Builder JA product. % 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)
For reference, the code of displayObj.m is displayed here:
function className = displayObj(h)
%DISPLAYOBJ Display information about a Java object
% This file is used as an example for the
% MATLAB Builder JA product.
h
className = class(h)
whos('h')
methods(h)While in MATLAB, issue the following command to open the Deployment Tool window:
deploytool
You create a Java application by using the Deployment Tool GUI to build a Java class that wraps around your MATLAB code.
To compile or build the Java application using the Deployment Tool, use the following information as you work through this example in Building the Java Component:
| Project Name | OptimDemo |
| Class Name | Optimizer |
| File to compile | doOptim.m 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:
/* BananaFunction.java
* This file is used as an example for the MATLAB
* Builder JA product.
*
* Copyright 2001-2011 The MathWorks, Inc.
* $Revision: 1.1.6.6 $ $Date: 2011/10/31 03:01:33 $
*/
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;
}
}
The class implements the Rosenbrock banana function described in the fminsearch documentation.
Write source code for an application that accesses the component. The sample application for this example is in ObjectRefExample\ObjectRefDemoJavaApp\PerformOptim.java. The program listing is shown here:
/* PerformOptim.java
* This file is used as an example for the MATLAB
* Builder JA product.
*
* Copyright 2001-2011 The MathWorks, Inc.
* $Revision: 1.1.6.6 $ $Date: 2011/10/31 03:01:33 $
*/
/* 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 Builder component 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();
}
}
}
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
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 matlabroot argument. For example, there should be no space between javabuilder.jar; and .\distrib\OptimDemo.jar in the following example.
Open a Command Prompt window and cd to the matlabroot\ObjectRefExample folder.
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 -d64 flag in the Java command. See Limitations and Restrictions for more specific information. |
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
![]() | Phonebook Example | Web Application Example | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2012- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |