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

Thread Subject:
for-loop vectorization

Subject: for-loop vectorization

From: Michal Kvasnicka

Date: 6 Oct, 2012 09:08:07

Message: 1 of 4

How to effectively vectorize this code?

for i=1:n
    a(i,:) = b(i,c(i,:));
end

Thank in advance for eny help.

Subject: for-loop vectorization

From: Matt J

Date: 6 Oct, 2012 09:34:08

Message: 2 of 4

"Michal Kvasnicka" wrote in message <k4osdn$35k$1@newscl01ah.mathworks.com>...
> How to effectively vectorize this code?
>
> for i=1:n
> a(i,:) = b(i,c(i,:));
> end
>
> Thank in advance for eny help.

I=repmat((1:n)',1, size(c,2));

a=b( sub2ind(size(b), I,c ) );

Subject: for-loop vectorization

From: Bruno Luong

Date: 6 Oct, 2012 09:52:08

Message: 3 of 4

Anther solution:

% assuming size(b,1)=n
a = b(bsxfun(@plus,(1:n)',(c-1)*n);

% Bruno

Subject: for-loop vectorization

From: Michal Kvasnicka

Date: 8 Oct, 2012 12:35:08

Message: 4 of 4

"Bruno Luong" <b.luong@fogale.findmycountry> wrote in message <k4ov07$bfc$1@newscl01ah.mathworks.com>...
> Anther solution:
>
> % assuming size(b,1)=n
> a = b(bsxfun(@plus,(1:n)',(c-1)*n);
>
> % Bruno

Thanks Bruno ... as always your solution is very good.
Michal

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us