how do you sum using loop?

조회 수: 3 (최근 30일)
anna
anna 2021년 8월 31일
편집: John D'Errico 2021년 9월 1일
for example I have f(x)= x(x+1), and I want f(1)+f(2)+...+f(100). How to sum using loop , I know Total_sum works too. But I do not know other way.

답변 (1개)

Wan Ji
Wan Ji 2021년 8월 31일
편집: Wan Ji 2021년 9월 1일
x=1:100;
f=@(x)x.*(1+x);
S=sum(f(x));%this should be ok
%or use loop
f=@(x)x.*(1+x);
S=0;
for i=1:100
S=S+f(i);
end
disp(S)
Answer
343400
  댓글 수: 1
John D'Errico
John D'Errico 2021년 9월 1일
편집: John D'Errico 2021년 9월 1일
x=1:100;
f=@(x)x.*(1+x)
f = function_handle with value:
@(x)x.*(1+x)
S=sum(f(x));%this should be ok
S
S = 343400
So f is a function handle. It is vectorized, so that when you pass in a vector of length 100, f(x) returns a vector of elements, of length 100. Now sum sums the vector, so your first solution will work.
But now look at the code you wrote in the loop. In there, you treat f as a VECTOR, forgetting that f is a function handle, NOT itself a vector.
The other thing I would do is to change the loop. That is, rather than hard coding the number of terms in the loop, do this:
x=1:100;
f=@(x)x.*(1+x);
S=0;
for i=1:numel(x)
S=S+f(x(i));
end
disp(S)
343400
You should see that I made two changes. I set the length of the loop to be the length of x. Hard coding the length of a loop there is asking for a bug to happen, when tomorrow arrives and you change the length of x. Now the loop is either too long or too short. In either case, you create a bug.
More important of course, was the change in this line to read:
S=S+f(x(i));
Again, f is a function handle. You cannot index into a function handle.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile 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