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.
4 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(1 个)
Paul
2023-9-13
编辑:Paul
2023-9-14
If you want both outputs returned, use ouput arguments on the call
[m,n] = save_13(1,2)
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)
If you want only the first output in a particular variable in the workspace
m = save_13(1,2)
If you want only the second ouput
[~,n] = save_13(1,2)
function [x,y] = save_13(a,b)
x = 5 + a;
y = 7 + b;
end
3 个评论
Walter Roberson
2023-9-14
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.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!