MATLAB Answers


I need to know how matlab do A(B) where A and B are 2 vectors

Asked by Mousa
on 17 Nov 2012


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


C=[2 1 4 9]

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

for i=1 to 4

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


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

@Matt J: C = A(B) is not and should not be multi-threaded, because B is 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.

Log in to comment.

1 Answer

Answer by Loginatorist 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.


I think is inside matlab not inside library for c Language

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

Log in to comment.

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today