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.

回答(1 个)

Cam Salzberger
Cam Salzberger 2019-11-13
Hello Brandon,
You can opt to ignore the first output using a tilde:
[~, var2] = name(in1, in2);
Is that what you were looking for?
-Cam
  2 个评论
Brandon Chapman
Brandon Chapman 2019-11-13
hmm, I want to use the second output later on in the main code. So I need to assign it to a varriable to make it quicker to call. Instead of using [~, var2] = name(in1, in2); to only get the second out, I want to use "var2" to call the function. I'm not used to matlab and use Java for a lot of things so maybe it's not possible? It's for school assignment.
Cam Salzberger
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by