MATLAB Answers

Any way to assign the second output to a variable on a function?

13 views (last 30 days)
Brandon Chapman
Brandon Chapman on 13 Nov 2019
Commented: Cam Salzberger on 13 Nov 2019
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.


Sign in to comment.

Answers (1)

Cam Salzberger
Cam Salzberger on 13 Nov 2019
Hello Brandon,
You can opt to ignore the first output using a tilde:
[~, var2] = name(in1, in2);
Is that what you were looking for?


Brandon Chapman
Brandon Chapman on 13 Nov 2019
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 on 13 Nov 2019
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;
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
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;
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
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?

Sign in to comment.

Sign in to answer this question.