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

 採用された回答

Andrei Bobrov
Andrei Bobrov 2012 年 2 月 7 日

0 投票

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

2 件のコメント

Titus Edelhofer
Titus Edelhofer 2012 年 2 月 7 日
You might also use
x = linspace(0, 1, n);
Asit
Asit 2012 年 2 月 7 日
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.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索

製品

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by