Effacer les filtres
Effacer les filtres

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

18 vues (au cours des 30 derniers jours)
Kristen O'Mara
Kristen O'Mara le 22 Fév 2018
Commenté : Khondaker le 2 Avr 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 commentaires
Jan
Jan le 24 Fév 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 le 25 Fév 2018
Jan Simon: sometimes people coming from C++ and other languages do not realise how compact MATLAB can be.

Connectez-vous pour commenter.

Réponses (2)

James Tursa
James Tursa le 22 Fév 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 commentaires
Anita Osoh
Anita Osoh le 1 Nov 2020
what would u enter??
Khondaker
Khondaker le 2 Avr 2023
Shall I enter userNum? But still it didn't work

Connectez-vous pour commenter.


Jan
Jan le 22 Fév 2018
Modifié(e) : Jan le 24 Fév 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.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by