How to make a for loop that sums all the odd values in the array?

43 次查看(过去 30 天)
I need to make a for loop that sums all the odd values in an array from 1 to userNum. This is what I have so far:
function [summedValue] = OddSum(userNum)
for i = 1:2:userNum
summedValue = sum(i);
end
When the user number is 5 I'm getting 5 as an output when I should be getting 9. I thought when I used the for-loop it made an array [1, 3, 5] because of the counter equalling 2. Then when I typed summedValue = sum(i) I thought it would take the sum of all the elements of the array.
  3 个评论
Jan
Jan 2018-2-24
@John BG: The explanation is:
I need to make a for loop that sums all the odd values
Then omitting the loop is interesting (and has been mentioned in my answer already), but not wanted.
John BG
John BG 2018-2-25
Jan Simon: sometimes people coming from C++ and other languages do not realise how compact MATLAB can be.

请先登录,再进行评论。

回答(2 个)

James Tursa
James Tursa 2018-2-22
Initialize your summing variable prior to the loop:
summedValue = 0;
Then inside the loop, add to it:
for i = 1:2:userNum
summedValue = summedValue + __________;
end
You need to fill in the blank with appropriate code.

Jan
Jan 2018-2-22
编辑:Jan 2018-2-24
You can set a breakpoint in the code and step through it line by line. This let you see, what's going on. You can examine directly, that sum(i) replies i, because it is a sum of a single element. Then summedValue is overwritten in each iteration. See James' answer.
By the way: While you are wanted to use a loop, you can do this much nicer in Matlab:
v = 1:2:userNum
Now you have a vector of the numbers and sum() adds all elements of a vector.
And of course, Gauss would do this with a tiny formula instead of processing all elements individually.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by