Unexpected behaviour when calling main function with 2 outputs
Show older comments
For this function, I'm expecting 2 outputs when I run the script (n,p). However, I only get one 'n' when I run. Why?
function [n, p] = SandboxFile()
clear all
clc
n = 5;
p = 6;
end
3 Comments
N/A
on 24 Mar 2019
Walter Roberson
on 24 Mar 2019
[outputs{1:1000}] = function_that_returns_1000_outputs();
Walter Roberson
on 24 Mar 2019
I am wondering why Matlab is not able to recognize the number of outputs and return me all those outputs instead of manually having to type in the command window n,p.
The reason that it cannot do that is that there is no connection between the dummy variable names used as the output variables in the function, and the names of similar variables in the workspace of the caller.
The entire purpose of functions is encapsulation so that the implementation of the function is hidden and cannot interfere with the calling function. The calling function should not have to know or care whether the called function uses particular internal variable names.
Consider the sequence
abc = 123;
some_function();
disp(abc)
In any reasonable programming language, provided the implementator of some_function does not deliberately override normal operations, abc would still be 123 after some_function() is called no matter which variables some_function uses internally. The result of those statements should not vary if the interface definition is
function abc = some_function()
compared to if the interface definition is
function av34va_3uja = some_function()
If, as you propose, it did matter, and that abc or av34va_3uja would be assigned to in the calling function if the user did not specify all of the destination variables, then in order to deliberately write safe code it would be necessary to predict which variable names that the calling function might accidentally use internally, in order to avoid writing over those variables when the user did not want that. And woe is you if you are making recursive calls and so cannot possibly avoid having an output variable name that is used in the caller.
WIth the current definition of MATLAB, there is no chance of accidentally overwriting a variable that the user did not ask to be assigned to -- not unless the person writing the function deliberately uses assignin('caller') (or you use global variables.) With the definition of MATLAB that you propose, you would have to go to lengths to prevent accidentally overwriting variables in the caller. It is not a good scene.
Accepted Answer
More Answers (0)
Categories
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!