# Help me differentiate between two codes??

1 view (last 30 days)
Radhika on 22 Oct 2014
Commented: Radhika on 30 Oct 2014
I'm trying to understand how to use for loops and if statements in school.
I wrote a function to try to sum certain elements in a vector that are between two set parameters.
The correct function code is
function [Sum] = summing (x,a,b)
%x being a vector, a&b are the parameters
Sum = 0;
for k = 1: length(x)
if ((x(k)>=a) & (x(k)<=b))
Sum = Sum + x(k);
end
end
end
so for example is I wanted to add all the elements of vector x that are between 1 and 3 I would enter
x = [0,1,2,4,3];
summing(x,1,3)
ans = 6
I've tested this and I am content with it.
However my first attempt was to create the function
function [Sum] = Summing (x,a,b)
Sum = 0;
for k = 1:length(x)
if (a<=x(k)<=b)
Sum = Sum + x(k);
end
end
end
using the same input as before:
x = [0,1,2,4,3];
summing(x,1,3)
ans=10
I get a totally different wrong answer. Obviously my if statement is different, but I am curious as to
why the output is so different.
Can anyone enlighten me as to how my second code works? like what exactly is happening in it?
##### 0 CommentsShow -1 older commentsHide -1 older comments

Sign in to comment.

### Accepted Answer

Matt Tearle on 22 Oct 2014
Edited: Matt Tearle on 22 Oct 2014
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!
##### 1 CommentShow NoneHide None
Radhika on 30 Oct 2014
Thanks so much!

Sign in to comment.

### Categories

Find more on Code Performance in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!