tags:

views:

69

answers:

2

Hi. I want to speedup some matlab code involving a loop. A common solution is to code the loop in C and call it from matlab. However, I was wondering if I can get similar benefits from implementing the loop in Java instead - perhaps the just-in-time compilation makes it faster?

+4  A: 

Before you start working with outside code: Have you pre-allocated your variables? Can you vectorize your loop? While the Matlab just-in-time compiler has become a lot better over the years, there are still cases where vectorization brings significant improvement. Also, note that quite a few Matlab functions (those for which you don't see code when you open them in the editor) are implemented in C or Fortran, so you may not observe a dramatic speed gain.

If you can't speed up your Matlab code by better writing it in Matlab, and if it does look likely that reimplementing might actually bring you any benefit, then C might be fastest, though Java might be not too far behind (again it depends on the code you want to speed up - it might be a good idea if you posted it here). If you're much more familiar with Java than C, I suggest trying to go the Java route.

Jonas
Yes - I am very sure that I cannot vectorize my loop. About preallocating memory: I am not doing something like: for i=1:100, v(end+1) = xyz; end - but there are some variables created and manipulated inside the loop.Also, though I am aware that matlab uses very efficient linear algebra routines, I was hoping that the savings from eliminating the 'interpretation at runtime' cost would be significant.
vishvAs vAsuki
@vishvAs vAsuki: If the loop is complex and there is a large number of iterations, you should be able to eliminate some function call overhead, which can indeed bring execution times down.
Jonas
So I implemented my function in Java, taking advantage of the colt library. Initially I thought that it takes longer, but later I found that, once the classes are loaded, the Java code is about 2x faster! [I also found this relevent speed comparison - http://www.cs.yale.edu/homes/spielman/ECC/speedTests.html ]
vishvAs vAsuki
@vishvAs vAsuki: glad it worked. If you find my answer was useful, please consider accepting it.
Jonas
+1  A: 

People on SO are always eager to help on optimizing code. Once you've spotted the time consuming code section by profiling, you might publish a code extract here.

One phenomenal MATLAB feature is its ability to do JAVA scripting. Write your 'optimized' code in JAVA and instantiate the class within MATLAB. Using C your forced to write a wrapper, which is not as seamless.

zellus