Calling Matlab From Java
Here is a class I built as part of my matlab distributed computing tool. It uses Java 1.5 with generics and variable argument lists to create a reasonably simple interface to Matlab functions.The function object is thread safe and blocks until matlab returns the result.
import com.mathworks.jmi.*; import java.util.concurrent.*; /** * Represents a blocking matlab function call. Adds the ability to call a matlab * function in a thread safe manner. The function call to execute the matlab * function takes a variabe length argument list. * * @author Brad * */ public class MatlabFunction<T> { private class Completion implements CompletionObserver { private T returnValue; private Semaphore semaphore = new Semaphore(0); /* * * @see com.mathworks.jmi.CompletionObserver#completed(int, * java.lang.Object) */ @SuppressWarnings("unchecked") public void completed(int arg0, Object arg1) { returnValue = (T) arg1; semaphore.release(); } T getReturnValue() { try { semaphore.acquire(); return returnValue; } catch (InterruptedException e) { return null; } } } /** The name of the matlab function */ String function; /** Handle to the matlab object */ Matlab matlab = new Matlab(); /** * Create a thread safe blocking matlab function object * * @param function * The name of the matlab function */ public MatlabFunction(String function) { this.function = function; } /** * Execute the matlab function * * @param args * Variable input arguments * @return the result of the matlab function. */ public T execute(Object... args) { Completion completion = new Completion(); matlab.feval(function, args, completion); return completion.getReturnValue(); } }
Use the class like
MatlabFunction<double []> f = new MatlabFunction<double []>("times"); double x[] = f.execute(10,20);
The function should return the value 20
Just remember that you can't call this from the Matlab command line. It will deadlock and hang your Matlab. This should only be run from a seperate thread not directly invoked by the Matlab thread.
If you get a ClassCastException when running this then Matlab is returning a datatype different to what you have specified in the generics specification. Use a debugger to figure out what kind of datatype is being returned by matlab.