How to create a loop with the sum adding up to a given N?

조회 수: 11 (최근 30일)
Muhammad Akhtar
Muhammad Akhtar 2016년 10월 5일
편집: Matthew Eicholtz 2016년 10월 5일
The bread-and-butter of any program language is its ability to perform repeated calculations in a “loop”. Variables are often incremented within loops. The statement x = x+ 5; doesn’t make sense mathematically, but it makes perfect sense to Matlab that evaluates the statement to the right of the equals sign first, and then makes the variable on the left equal to this new value. In other words,
x = 0;
for i=1:10
x = x+1;
end
will start off setting x equal to 10, and then will execute a loop 10 times, where each time through it will increment x by 1. When it finishes, x will equal 10.
Modify the following program below so that it returns the sum of the numbers from one to N. Call the program PyramidSum, and test that PyramidSum(10) returns 1+2+3+4+... 55.
function CountUpToN(N)
for i=1:N
disp(i)
end

답변 (2개)

Massimo Zanetti
Massimo Zanetti 2016년 10월 5일
There is a well-known formula by Gauss
x= n(n+1)/2;
  댓글 수: 1
Jan
Jan 2016년 10월 5일
+1: Even if Matlab's sum(1:n) looks so nice, using a brain is more efficient.

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


Matthew Eicholtz
Matthew Eicholtz 2016년 10월 5일
This sounds like a homework problem. The answer is basically already in the question.
N = 10;
x = 0;
for ii=1:N
x = x+ii;
end
But, for what it's worth, this is not the best way to sum numbers from 1 to N in MATLAB. Try something like:
x = sum(1:N);
  댓글 수: 3
Matthew Eicholtz
Matthew Eicholtz 2016년 10월 5일
function y = fcn(x)
y = sum(1:sum(1:x));
end
Matthew Eicholtz
Matthew Eicholtz 2016년 10월 5일
편집: Matthew Eicholtz 2016년 10월 5일
Or if you want to go Massimo's suggested route:
function y = fcn(x)
n = x*(x+1)/2;
y = n*(n+1)/2;
end

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

카테고리

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