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?
Best Answer