Hi, can any body suggest as to how I can vectorize this little bit of code:
% for i = 2:n % f(i) = f(i-1)+dx*x(i-1); % end
where, f = zeros(1,n); dx = 1/(n-1); x = 0:dx:1;
appreciate any help, because I am kind of stuck and right now don't think it can be done at all. Thanks, Asit

 Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 7 de Feb. de 2012

0 votos

dx = 1/(n-1);
x = 0:dx:1;
f = [0 cumsum(dx*x(1:end-1))]

2 comentarios

Titus Edelhofer
Titus Edelhofer el 7 de Feb. de 2012
You might also use
x = linspace(0, 1, n);
Asit
Asit el 7 de Feb. de 2012
Hi Andrei, thanks a lot for your response.
It would be very helpful for using in situations with multiple such loops.
I was so busy trying to trick a way out that I forgot about the built in cumulative summation feature. :P
As others might have guessed, for this particular example though, the loop seems to be slightly faster.
Titus: I am bit shaky on the differences between using 1:dx:b and linspace. Generally, if I know the number of divisions I want, I go for linspace, if I know their size, I go for the a:dx:b thing. In this case both are known, though linspace requires 1 less operation. Any other advantages I am missing?
Thank you both,
a.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.

Productos

Etiquetas

Preguntada:

el 7 de Feb. de 2012

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by