I am trying to get my function to return two variables to the workspace. It is a very simple function. What am I doing wrong.

2 vues (au cours des 30 derniers jours)
function [x,y] = save_13(a,b)
x = 5 + a;
y = 7 + b;
% I should be gettting 'x' and 'y' to return to the workspace, as they are listed outputs. I don't get that. I only get the following:
>> save_13(1,2)
ans =
I presume I should be getting the following into my workspace: x = 6, y = 9, but I don't. Any ideas? Thank you very much.

Réponses (1)

Paul le 13 Sep 2023
Modifié(e) : Paul le 14 Sep 2023
If you want both outputs returned, use ouput arguments on the call
[m,n] = save_13(1,2)
m = 6
n = 9
When you call a function without output arguments, in general, only the first output is returned and is assigned to a workspace variable called 'ans'
ans = 6
If you want only the first output in a particular variable in the workspace
m = save_13(1,2)
m = 6
If you want only the second ouput
[~,n] = save_13(1,2)
n = 9
function [x,y] = save_13(a,b)
x = 5 + a;
y = 7 + b;
  3 commentaires
Walter Roberson
Walter Roberson le 14 Sep 2023
function [x,y] = save_13(a,b)
x = 5 + a;
y = 7 + b;
MATLAB interprets that more like,
function [convenient_name_for_first_output_position, convenient_name_for_second_output_position] = save_13(convenient_name_for_what_is_passed_as_first_parameter, convenient_name_for_what_is_passed_as_second_parameter)
whatever is in the first output position = 5 + whatever is in the first input position;
whatever is in the second output position = 7 + whatever is in the second input position;
The names on the left hand side of the = in the function line are placeholder names to make it easier to refer to what will be returned in the corresponding output positions. The names used inside the function statement do not refer to any variable names used anywhere else in any other function or workspace: they are only "nicknames" for the corresponding input or output positions. Assigning to an output parameter name inside a the same function never affects a variable of the same name in any other function or workspace.
There are ways in MATLAB where you can deliberately force a function to change a variable that is not in the current function, but not by way of assigning a value to a variable declared to the left of a = in the same function's function line.
Paul Mezs
Paul Mezs le 16 Sep 2023
Thank you for the explanation. It cleared things up. Much appreciated!

Connectez-vous pour commenter.


En savoir plus sur Startup and Shutdown dans Help Center et File Exchange




Community Treasure Hunt

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

Start Hunting!

Translated by