MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today
Asked by Mousa on 17 Nov 2012

let

A=[1 2 4 6 9] B=[2 1 3 5] C=A(B)

so

C=[2 1 4 9]

How is matlab do this very fast is used the following code

for i=1 to 4 c(i)=A(B(i) end

I think no since it do this very fast even if the vector size is 100000 so how is matlab do this

I need the answer since I need to program it in C to become fast as in matlab please any help

*No products are associated with this question.*

Answer by Matt Fig on 17 Nov 2012

I believe that these basic things are done just like you show, but in **compiled C-code.** Thus it is much faster that using interpreted MATLAB code, even with the JIT.

Show 7 older comments

Matt Fig on 18 Nov 2012

The mex function I posted above needs to be compiled by MATLAB to run. If you have never used MEX, you need to do this:

mex -setup

This will guide you through the process of finding a compiler on your system. I have used the Microsoft Software Development Kit (SDK) 7.1 for the above tests. Then make sure that the mex-file is on the MATLAB path to compile it. You also might want to do:

help mex

## 2 Comments

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/53986#comment_111652

How MATLAB accelerates its code is not public domain knowledge, but it is likely that multithreading is involved.

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/53986#comment_111749

@Matt J:

C = A(B)is not and should not be multi-threaded, becauseBis not necessarily unique. Therefore there is no strategy to distribute the job to multiple workers.An important difference between this Matlab code and a naive C-implementation is the range check. The C-code is much slower, if the limits are checked in each iteration, because the required IF branching prevents a successful pipelining of the code inside the processor.

Unfortunately a range check seems to happen for logical indexing also. A C-code implementation takes less than the half time, if it performs only 1 check of the length of the index array.