Ah, yes. This curious bit of syntax. What you ended up with was sum(x)! Why? Well, MATLAB evaluates the first condition a <= x(k). This returns either 1 (true) or 0 (false). Then there's a second condition (previous result) <= b. Given that b = 3, and the previous result is 0 or 1, this is always true! Hence all the elements of x are added to your sum.
IOW, a <= x(k) <= b is parsed as ((a <= x(k)) <= b), and T/F in MATLAB is equivalent to 1/0.
[Note: it's possible that the order of operations is the other
As an aside, I hope they will teach you this, but the best way to do this operation in MATLAB is
idx = (a <= x) & (x <= b);
mysum = sum(x(idx))
Logical indexing is sweet!
Best Answer