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

 采纳的回答

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