Help figuring out this Function file

This isnt HW, its a review for my final exam. I thought I had figured it out until I put in my own values and that just threw away my theory. Help please
  • function [ y ] = mysum2( x,a,b )
  • sum=0;
  • for k=1:length(x)
  • if a<=x(k)<=b
  • sum = sum+x(k);
  • end
  • end
  • y=sum;
  • end
plug in array b b=[4 14 6 3 4 10 8 6]
y=mysum(b,-5,0) y=0
y=mysum(b,1,3) y=55
y=mysum(b,6,7) y=55
y=mysum(b,60,70) y=55
plug in array c=[3 -2 4 4 5 1 -4 -2 7] y=mysum(c,-10,-6) y=0
y=mysum(c,-2,0) y=-4
y=mysum(c,-2,-2) y=16
y=mysum(c,6,7) y=16

 채택된 답변

James Tursa
James Tursa 2013년 4월 19일
편집: James Tursa 2013년 4월 19일

1 개 추천

Your test should be:
if a<=x(k) && x(k)<=b
Your original line is interpreted as follows:
if (a<=x(k))<=b
The first test gives a logical result, which is going to work out to be 1 <= b or 0 <= b depending on the logical result of the first a <= x(k). This is of course not what you intended.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Dates and Time에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by