input and output function

1 次查看(过去 30 天)
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 中查找有关 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