MATLAB Answers

putting return to a function

136 ビュー (過去 30 日間)
Salvatore Mazzarino
Salvatore Mazzarino 2012 年 10 月 13 日
コメント済み: Image Analyst 2021 年 7 月 20 日 1:22
I have created a function "my_function" and into it I call another function called "another_function".
function my_function()
value = another_function(foo);
My question is: inside another_function(), do I need to put a line of code that says "return", or I may omit the return keyword and simply return automatically by finishing executing all lines of "another_function()"?

回答 (3 件)

Star Strider
Star Strider 2012 年 10 月 13 日
The documentation for Nested Functions says:
Typically, functions do not require an end statement. However, to nest any function in a program file, all functions in that file must use an end statement.
So another_function has to have an end statement.
  5 件のコメント
Image Analyst
Image Analyst 2021 年 7 月 20 日 1:22


Image Analyst
Image Analyst 2012 年 10 月 13 日
You can put returns wherever necessary in the function. At the end of the function it is optional (not necessary) but you can if you want
  1 件のコメント
Image Analyst
Image Analyst 2021 年 7 月 20 日 1:17
@Brianna Biondo, for example, in the file my_function.m you would have all these lines of code:
function my_function()
% Assign some input value that we will pass to another_function().
foo = 37.4;
% Pass the input value to another_function().
value = another_function(foo);
% Now print its value to the command window.
fprintf('After calling "another_function(%f)", we get value = %f.\n', foo, value);
% Now declare another function below the main function that has the name of the script.
% This function can be below the main my_function function in the same m-file,
% OR in a different m-file called "another_function.m".
function outputValue = another_function(inputValue)
outputValue = 10 * inputValue;
return; % This line is completely optional.


Matt Fig
Matt Fig 2012 年 10 月 13 日
編集済み: Matt Fig 2012 年 10 月 13 日
Salvatore, are you asking how to make the function return the value that will be assigned to 'value' inside my_function? In MATLAB, unlike some other languages, there is no need to tell the function which value to return to the caller by a special call to the return keyword. For example, put this in your local directory:
function out = mysquarefcn(in)
out = in.*in;
Once you save that as mysquarefcn.m, the from the command line call it like this:
>> mysquarefcn(3)
>> G = mysquarefcn(3)

Community Treasure Hunt

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

Start Hunting!

Translated by