MATLAB Answers

0

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

Asked by Brandon Chapman on 13 Nov 2019 at 19:23
Latest activity Commented on by Cam Salzberger on 13 Nov 2019 at 19:56
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 Comments

Sign in to comment.

Tags

Products

1 Answer

Answer by Cam Salzberger on 13 Nov 2019 at 19:26

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 Comments

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.
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?

Sign in to comment.