Can I supply Java objects or methods to functions (such as FMINCON) that expect MATLAB function handles?

1 view (last 30 days)
I would like to use 'function' functions, such as optimization routines, on Java objects or methods in addition to MATLAB function handles. This would be particularly useful with MATLAB Builder for Java, as I could then define Java routines and pass them into a MATLAB optimization back end.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
This enhancement has been incorporated in Release 2007a (R2007a). For previous product releases, read below for any possible workarounds:
The ability to apply 'function' functions such as FMINCON to Java objects or methods is not available in MATLAB.
To work around this issue, you may be able to wrap your Java method in an M-function that supplies the appropriate interface. This will require that the Java method provides the same functionality as the expected function handle.
For example, to use FPLOT to plot a simple quadratic, you would normally use a function handle:
fplot(@(x) x.^2, [-2 2])
You could achieve the same using a Java class, with a static method, by using a wrapper function. The Java class could be defined as follows:
public class Dydt {
public static double deriv(double t)
{
return t * t;
}
}
You could then use the following wrapper to plot the function defined by the Java method:
fplot(@(x) Dydt.deriv(x), [-2 2])
More complicated situations, such as methods with additional arguments, or methods of a particular instantiated object, would require more complicated wrapper functions.
For information about using C or shared library functions with FMINCON, or other M-functions which take an M-function handle as input, please see the Related Solution below.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!