Write a function called mysum that sums the first n positive numbers. Give the result x1 for n=20,and the result x2 for n=100. For example, if n = 2, mysum computes the sum of 1 and 2. The result is 3.

조회 수: 7 (최근 30일)
I tried using a for loop setting
mysum = 0;
for k= 1;n
mysum = k+n;
end
mysum
  댓글 수: 1
Walter Roberson
Walter Roberson 2019년 9월 4일
Functions start with the key word "function".
MATLAB uses colon between start and end point in a for loop, not semi-colon. k=1:n not k=1;n
Your algorithm is not correct: you are not totalling anything, you overwriting all calculations done so far each iteration of the for loop.

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

답변 (1개)

Devineni Aslesha
Devineni Aslesha 2019년 9월 9일
Create a function using the keyword ‘function’ and save the file with name mysum.m.
function output = mysum(n)
output = 0;
for k = 1:n
output = output + k;
end
end
To get the sum of first 10 positive numbers, call the function using the below syntax.
output = mysum(10)
Doc Link:

카테고리

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