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에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

태그

질문:

2012년 2월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by