Running a sum function using a for loop?

조회 수: 4 (최근 30일)
laty ag
laty ag 2015년 7월 15일
편집: Jan 2015년 7월 15일
I am running the following script: function[x]=sum1 (x,a,b)
total=0;
For k=1:length(x)
if a <=x(k)<=b
total=total+x (k);
end
end
y=total
end
On the command window i state
b= 4 14 6 3 4 10 8 6
y1=sum1(b,-5,0)
Ans=0
y2=sum1 (b,1,3)
Ans=55
I don't understand how this is obtain. I would think the answer is 3. Because what I'm trying to do is to add the number of b that fall between 1 and 3.

채택된 답변

bio lim
bio lim 2015년 7월 15일
function[x]=sum1 (x,a,b)
total=0;
for k=1:length(x)
if x(k) >= a & b >= x(k)
total = total + x(k);
end
end
y = total
end
You can't write if a <=x(k)<=b. You must use the & expression.

추가 답변 (1개)

Jan
Jan 2015년 7월 15일
편집: Jan 2015년 7월 15일
a <= x(k) <= b is evaluated from the left to the right:
  1. a <= x(k) : This is either true or false, which is treated as 1 or 0
  2. 1 <= b or 0 <= b
This is not what you want. As posted already use the & operator or better &&.
By the way: You do not need a loop. This is nicer and faster:
total = sum(x(a <=x & x<=b));

카테고리

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