MATLAB Answers

Why in a function an output argument isn't saved to workspace?

2 views (last 30 days)
function This_is_the_output_I_want_to_save_to_workspace = MyFunc(~)
My_input = input ('Enter input here: ');
This_is_the_output_I_want_to_save_to_workspace = My_input^2;
end
  2 Comments
Rik
Rik on 24 Apr 2021
Matlab stored it in the ans variable, just like you asked it to do.

Sign in to comment.

Accepted Answer

John D'Errico
John D'Errico on 24 Apr 2021
Edited: John D'Errico on 24 Apr 2021
Suppose you use ANY MATLAB function? How does it work? For example...
x = 1:5;
Suppose you want to compute the mean of that vector? Do you do it like this?
mean(x);
If you do, then where does the result get stored?
whos
Name Size Bytes Class Attributes ans 1x1 8 double x 1x5 40 double
If you look, the result got dumped unceremoniously into ans. You need to put it INTO somethign to get stored. The name in the function definition does nothing, except tell MATLAB which variable to return.
If you want to put it into something, then you do this:
result = mean(x);
whos
Name Size Bytes Class Attributes ans 1x1 8 double result 1x1 8 double x 1x5 40 double
Now a result exists in a variable with my choice of name, NOT in ans.
When you return a variable, you need to remember the name of that variable when inside the function is not retained. The outside world does not know anything about the variable names inside your function.
  4 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!