Asked by Mohsen
on 14 Jun 2013

How can I optimize (vectorize?) the following code in order to avoid the for loop and make the code to run faster?

for i=1:55; A(i)=B((i-1)*3+1,1); end

A is 1 x 55 and B is 165 x 1

Many thanks!

Answer by Laila Kazemi
on 14 Jun 2013

C= B*3 +1 A (1:55, 1:55)= C(1:55, 1)

but the dimensions of ur matrices dont match , if B was 55 by 1 , it would have worked

Mohsen
on 16 Jun 2013

Thanks for your answer but it doesn't seem to be the right answer... Please note that the multiplication by 3 and the addition by 1 is used to access the content of each element and not to modify the content of the elements...

I found this answer and it worked:

A=B(1:3:55*3,1);

Thanks again.

Answer by Andrei Bobrov
on 14 Jun 2013

A(1,:) = B((0:size(A,2)-1)*3+1);

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

Learn moreOpportunities for recent engineering grads.

Apply Today
## 3 Comments

## Matt Kindig (view profile)

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/79109#comment_155020

This loop will make A only 1x55, not 55x55.

## Laila Kazemi (view profile)

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/79109#comment_155023

bc ur only assigning one raw to A

## Mohsen (view profile)

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/79109#comment_155029

You are both right!

A is 1 x 55

Do you know how to optimize the for loop? Thanks!