input and output function

조회 수: 1 (최근 30일)
Brooks Nelson
Brooks Nelson 2017년 2월 19일
댓글: Divyang Jain 2019년 5월 31일
I have been trying to learn functions but must have a mental block. I am trying to take a number "n" as an input and output the sum of numbers up to "n" (Inclusive). For example, if input is 10, the program would output 55. I wrote the following.
function sum = sumNum(n)
end
I know I am missing something. Can some one help me. Thanks.
  댓글 수: 1
Divyang Jain
Divyang Jain 2019년 5월 31일
U haven't given any statment inside function sum so u will not recieve any output so try giving a statment inside a loop and then try

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

채택된 답변

Star Strider
Star Strider 2017년 2월 19일
Please do not use ‘sum’ as a variable. This is called ‘overshadowing’ so MATLAB will try to use your variable instead of the function, throwing an error that could be difficult to find.
An anonymous function version would be:
My_Sum = @(n) sum(1:n); % Anonymous Function Version
A function file version would be:
function y = My_Sum(n)
y = sum(1:n);
end
Both functions would return:
My_Result = My_Sum(10)
My_Result =
55

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB Coder에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by