Saturday, February 18, 2012

How to call Matlab functions from a Java program

Matlab is a very reputed piece of software specially among researchers and graduate students. It allows users to code complicated algorithms thanks to its rich libraries that implement many mathematical functions and statistical models. You may have ever used it to implement some classification processes that deals with heterogeneous data and you have got some interesting results and you wanted to show it to a client. He may not be interested in your statistical model nore in your charts and graphs. He is interested in a beautiful application with an ergonomic user interface with big shiny buttons that allow him to use you piece of program. He is interested in the usability of your program more than the academic process that allowed you to get your result.

So to make this happen, you need to implement a simple prototype that calls your Matlab functions and show resluts in a simple GUI. If you're a Java savvy, or you prefer java to make this happen you need to use the MatlabControl API. It's a simple Java API that allows you to call Matlab functions and execute eval, feval and other commands.

All you need to do is to download the jar file and add it to your classpath and use this code to open a Matlab session.

MatlabProxyFactoryOptions options = new MatlabProxyFactoryOptions.Builder()


MatlabProxyFactory factory = new MatlabProxyFactory(options);

MatlabProxy proxy = factory.getProxy();

After that you need to change your Matlab current path to your Matlab script path using CD command and then you can execute call your function:

proxy.eval("cd C:/Users/MyName/Desktop/MyScriptFolder");

If you need other details about variables and parameter you can use the API Walkthrough or check out the API Javadocs.