vectorization

6 views (last 30 days)
Asit
Asit on 7 Feb 2012
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

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 7 Feb 2012
dx = 1/(n-1);
x = 0:dx:1;
f = [0 cumsum(dx*x(1:end-1))]
  2 Comments
Titus Edelhofer
Titus Edelhofer on 7 Feb 2012
You might also use
x = linspace(0, 1, n);
Asit
Asit on 7 Feb 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.

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!