Clear Filters
Clear Filters

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 views (last 30 days)
function [x,y] = save_13(a,b)
x = 5 + a;
y = 7 + b;
end
% 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 =
6
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.

Answers (1)

Paul
Paul on 13 Sep 2023
Edited: Paul on 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'
save_13(1,2)
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;
end
  3 Comments
Walter Roberson
Walter Roberson on 14 Sep 2023
function [x,y] = save_13(a,b)
x = 5 + a;
y = 7 + b;
end
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;
end
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.

Sign in to comment.

Categories

Find more on Programming in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!