필터 지우기
필터 지우기

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

조회 수: 18 (최근 30일)
Kristen O'Mara
Kristen O'Mara 2018년 2월 22일
댓글: Khondaker 2023년 4월 2일
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.
  댓글 수: 3
Khondaker
Khondaker 2023년 4월 2일
Shall I enter userNum? But still it didn't work

댓글을 달려면 로그인하십시오.


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