Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return multiple output variables from Matlab function

Lets say I have a function:

function [ A, B, C ] = test(x, y, z)
    A=2*x;
    B=2*y;
    C=2*z;
end

When you press run, Matlab returns only the first value from the output arguments - [A] in this case. Is there a command that I can put inside my function that automatically returns all the function output arguments [A,B,C] instead of just the first argument. I know I can type in my command windows [ A, B, C ] = test(x, y, z) and get all the values, but I am lazy sometimes, and would just like to press Run and get automatically all the values.

like image 638
user3200392 Avatar asked Feb 18 '14 15:02

user3200392


People also ask

Can a MATLAB function return multiple variables?

Matlab allows you to return multiple values as well as receive them inline. Save this answer.

Can a function have two outputs?

Remember, in a function each input has only one output.


2 Answers

Some options:

Add a parameter to specify verbose output the console but set it to false by default:

function [ A, B, C ] = test(x, y, z, verbose)

   if nargin = 3
       verbose = false;
   end;

   A=2*x;
   B=2*y;
   C=2*z;

   if verbose
       fprintf('A = %f\nB = %f\nC = %f', A, B, C);
   end;

end

or combine them into one output:

function output = test(x, y, z)

   A=2*x;
   B=2*y;
   C=2*z;

   output = [A, B, C]; %// Or {A;B;C} if they're not going to be the same size, but then it won't display anyway

end

or if you really really want to I guess you could write a wrapper function that you call on your function and it displays all three for you that you could use generically on any function. But that hardly seems worthwhile.

like image 110
Dan Avatar answered Oct 04 '22 20:10

Dan


Another option is to use assignin to automatically save an output argument to the workspace

function [ A, B, C ] = test(x, y, z)
    A=2*x;
    B=2*y;
    C=2*z;

    assignin('base', 'A', A);
    assignin('base', 'B', B);
    assignin('base', 'C', C);      
end

'base' is the name of the main workspace used when you call variables from the command window.

This way you can type test(x,y,z) into the workspace without the [A,B,C] = part and it will still give you all the values.

The benefit of this over combing A, B and C into one output is that you will still have 3 seperate variables saved in your workspace. This is useful if A, B and C are arrays or cells. A disadvantage of this method is that if you use this function inside another function it will still only use the value of A. For example: length(test(x,y,z)) will just give the length of A.

like image 35
Blue7 Avatar answered Oct 04 '22 21:10

Blue7