Discover MakerZone

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

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

New to MATLAB?

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

Asked by Mousa

Mousa (view profile)

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

2 Comments

Matt J

Matt J (view profile)

on 17 Nov 2012

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

Jan Simon

Jan Simon (view profile)

on 18 Nov 2012

@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.

Mousa

Mousa (view profile)

Products

No products are associated with this question.

1 Answer

Answer by Matt Fig

Matt Fig (view profile)

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.

10 Comments

Mousa

Mousa (view profile)

on 18 Nov 2012

I think is inside matlab not inside library for c Language

Matt Fig

Matt Fig (view profile)

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
Mousa

Mousa (view profile)

on 18 Nov 2012

Thanks

Matt Fig

Matt Fig (view profile)

Contact us