Any way to assign the second output to a variable on a function?
45 次查看(过去 30 天)
显示 更早的评论
say you have some function, function [out1, out2] = name(in1,in2). You want to assign out2 to a variable. How would you go about doing that?
if you do, var1 = name(in1,in2), you get the first output and that is all.
0 个评论
回答(1 个)
Cam Salzberger
2019-11-13
Hello Brandon,
[~, var2] = name(in1, in2);
Is that what you were looking for?
-Cam
2 个评论
Cam Salzberger
2019-11-13
I'm confused by what exactly you are asking. Let me try to break it down, and share some terminology.
Let's say you have a file called "my_function.m" that contains a function definition. It looks something like this:
function [out1, out2] = my_function(in1, in2)
out1 = in1; % For simplicity
out2 = in2;
end
Sidenote: In MATLAB, the filename must match the name of the function it defines.
Now you have some other place that you want to call this function from. This could be within another function, a script, or even from the Command Window. Normally, you would call my_function by providing the inputs and accepting the outputs into variables. You could then go on to use those variables elsewhere in your code:
a = 1;
b = 2;
[x, y] = my_function(a, b);
theta = atan2(y, x); % Built-in arctan function, for example
disp(theta)
Sidenote: The variable names where you call the function, and the variable names in the function definition do not need to match.
Now MATLAB allows some flexibility in how you call and get data from functions. If you were only interested in the first output from the function, you could just only assign one output variable:
x = my_function(a, b);
area = x^2;
disp(area)
If you were only interested in the second output argument, you could ignore the first output:
[~, y] = my_function(a, b);
new_matrix = magic(y); % Another example function
disp(new_matrix)
I really don't know what you mean by "wanting to use var2 (which appears to be the output of my_function in our example) to call the function (again, my_function?)". Can you try again, showing a snippet of code maybe. Show how you want to call "my_function" and then how you want to use the output to call something else?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!