Easiest Way to Use Matlab over Java


I think Matlab is often needed for OR people, for solving equations, taking derivatives, etc.. Although I like mathematical software, I am using Object Oriented Programming instead, since I’m more familiar to them. However due to limitations of programming languages, we may need to use math software.

For my thesis coding I’m using Java. I need to solve an equation for my heuristic. I will go through this case. The equation I need to solve was;

There is a library “matlabcontrol” on the internet for connecting Matlab to Java. It allows to use Matlab commands (setting/getting variables, solving equations, returning operations). You can reach library here, and download here.

So, how could we use it? First of all import library to your project. If you are using eclipse, you can find how to import libraries from this link or video. After importing, we are ready to go.

MatlabProxyFactory factory = new MatlabProxyFactory();
MatlabProxy proxy = factory.getProxy();

This command will open a Matlab screen. Then for my case, I solve the equation by the following code;

String f = 'fsolve(@(a)integral(@(t)(10-t),0,a)-9,0)';
Object[] d = proxy.returningEval(f,1);

Here returningEval function run the command and return the output of the Matlab. fsolve is used to solve equation. It gives the result, where the function (first parameter) is zero. Therefore, I move “9” to left with minus sign.

Resulting array is outputs. What we need is the value of the “a”. So, using following codes will help me;

Object arg = d[0];
double result = ((double[]) arg)[0];

We did it! Finally we have the value of the “a”.

In this post, I tried to show a very simple way to connect Matlab to your Java code. If you have questions, I would be happy to answer.

(Photo by Marc Amos)

Sertalp Bilal Çay

PhD Candidate and Teaching Assistant in Industrial and Systems Engineering Department at Lehigh University. Researcher on Conic Optimization, Inventory Theory, Supply Chain Management and Simulation. Blog: sertalpbilal.com