Filter löschen
Filter löschen

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

18 Ansichten (letzte 30 Tage)
Kristen O'Mara
Kristen O'Mara am 22 Feb. 2018
Kommentiert: Khondaker am 2 Apr. 2023
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 Kommentare
Jan
Jan am 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 am 25 Feb. 2018
Jan Simon: sometimes people coming from C++ and other languages do not realise how compact MATLAB can be.

Melden Sie sich an, um zu kommentieren.

Antworten (2)

James Tursa
James Tursa am 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.
  3 Kommentare
Khondaker
Khondaker am 2 Apr. 2023
Shall I enter userNum? But still it didn't work

Melden Sie sich an, um zu kommentieren.


Jan
Jan am 22 Feb. 2018
Bearbeitet: Jan am 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.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by