Help me differentiate between two codes??
1 回表示 (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
Matt Tearle
2014 年 10 月 22 日
編集済み: Matt Tearle
2014 年 10 月 22 日
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!
その他の回答 (0 件)
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!