Saturday, May 3, 2014

Matlab and Java: Can’t everyone just get along?

I’m still not certain of the answer. I had come up with, what I thought, was a great idea of calling the Matlab implementations of the OSD and OCBA algorithms instead of trying to recreate them in Java. Great idea, right? Well, I have had a few hiccups along the way. Using the library created by Joshua Kaplan, I was excited when I was completed his “Hello World” example. I was so excited when I was able to call my Matlab functions from Java passing in arrays of data. Then the hard part came: passing in the stochastic function. Since I’m passing it in as a string, Matlab doesn’t want to just accept that I’m right and the string is actually a function. I was on the train so didn’t have any internet connectivity so I started searching through the Matlab help files. I found the function “Execute” that I foolishly believed was the answer to my prayers, for about 5 minutes. It did evaluate the function I sent in as a string, but then it returned a string. That was useless since I needed the evaluation later in the Matlab code. Of course this problem was bugging me so I Googled and found the wonderful function eval. This function truly is the answer to my problems so far. Just in case anyone else needed to do something as strange as this, I figured I would post some code samples to help. It is still a work in progress, but might serve as someone’s lifeline.
Java
RemoteMatlabProxyFactory factory = new RemoteMatlabProxyFactory();
RemoteMatlabProxy proxy = factory.getProxy(240000);
String functioName = "experiments";
Vector<Object> entries = new Vector<Object>();
entries.add(-1);
entries.add(-0.8);
entries.add(-0.6);
entries.add(-0.4);
entries.add(-0.2);
entries.add(0);
entries.add(0.2);
entries.add(0.4);
entries.add(0.6);
entries.add(0.8);
entries.add(1);
Vector<Object> newArray = new Vector<Object>();
newArray.add("ProbDistUnivParam('normal',[0 .6])");
newArray.add(entries.toArray());
Object[] input = newArray.toArray();
Object result = proxy.returningFeval(functioName,input);
 
Matlab
function m=experiments(probDistdb)
    pd=eval(probDist);
    [~,dim2]=size(db);
    db2=zeros(dim2,1);
    for i=1:dim2  db2(i)=db{i}; end
    m=osd(pd,db2,1,1000)
end         

I did notice during some of my experiments to see what all I could do that, if you pass back a double array (ans(3,3)), it becomes a single array with the second column just being appended to the end of the first. Just something to be aware of if you are passing back an array of arrays.

No comments:

Post a Comment