Clear Filters
Clear Filters

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

18 views (last 30 days)
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 Comments
Jan
Jan on 24 Feb 2018
@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 on 25 Feb 2018
Jan Simon: sometimes people coming from C++ and other languages do not realise how compact MATLAB can be.

Sign in to comment.

Answers (2)

James Tursa
James Tursa on 22 Feb 2018
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 on 22 Feb 2018
Edited: Jan on 24 Feb 2018
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.

Categories

Find more on Loops and Conditional Statements 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!