1

I use matlab to write a program with many iterations. It cannot be vectorized since the data processing in each iteration is related to that in the previous iteration.

Then I transform the matlab code to mex using the build-in MATLAB coder and the resulting speed is even lower. I don't know whether I need to write the mex code by myself since it seems the mex code doesn't help.

Amro
  • 123,847
  • 25
  • 243
  • 454
Hugo
  • 123
  • 4
  • possible duplicate of [Matlab mex file is slow compared to its straight C equivalent](http://stackoverflow.com/questions/5228388/matlab-mex-file-is-slow-compared-to-its-straight-c-equivalent) – TheCodeArtist Aug 07 '13 at 02:16
  • I don't think its a duplicate, that question was dealing with a specific case where the slowdown was happening at the MEX-MATLAB gateway level (according to the accepted answer this was fixed in R2011a), plus the OP was not even using MX-API functinos. Whereas this one is using *MATLAB coder* for code generation. That said this question cannot be reasonably answered in its current form, we need to see some code (for example what was the original MATLAB code, and what is the generated C code).. – Amro Aug 07 '13 at 02:46
  • 2
    Have you tried using Matlab's profiler tool and clock functions in C to figure out which parts take up the most time? And Amro's right, please post some code. – MattG Aug 07 '13 at 04:51

1 Answers1

0

I'd suggest that if you can, you get in touch with MathWorks to ask them for some advice. If you're not able to do that, then I would suggest really reading through the documentation and trying everything you find before giving up.

I've found that a few small changes to the way one implements the MATLAB code, and a few small changes to the project settings (such as disabling responsiveness to Ctrl-C, extrinsic calls back to MATLAB) can make give a speed difference of an order of magnitude or more in the generated code. There are not many people outside MathWorks who would be able to give good advice on exactly what changes might be worthwhile/sensible for you.

I should say that I've only used MATLAB Coder on one project, and I'm not at all an expert (actually not even a competent) C programmer. Nevertheless I've managed to produce C code that was about 10-15 times as fast as the original MATLAB code when mexed. I achieved that by a) just fiddling with all the different settings to see what happened and b) methodically going through the documentation, and seeing if there were places in my MATLAB code where I could apply any of the constructs I came across (such as coder.nullcopy, coder.unroll etc). Of course, your code may differ substantially.

Sam Roberts
  • 23,951
  • 1
  • 40
  • 64