Returns multiple output variables from a Matlab function

Lets say that 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, in this case matlab returns only the first value of the output arguments - [A] . Is there a command that I can embed in my function that automatically returns all the output arguments of the function [A,B,C] , and not just the first argument. I know that I can enter the commands [ A, B, C ] = test(x, y, z) in my windows and get all the values, but sometimes I'm lazy and just wanted to click Run and get all the values โ€‹โ€‹automatically.

+8
matlab
source share
4 answers

Some options:

Add a parameter to indicate verbose console output, but set the default value to false:

 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 me to write a wrapper function that you call in your function, and it displays all three for you, which you could use in general terms for any function. But it is hardly worth it.

+8
source share

Another option is to use assignin to automatically save the 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 invoking variables from the command window.

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

The advantage of this when combing A, B and C into one conclusion is that you still have 3 separate variables stored in your work area. This is useful if A, B, and C are arrays or cells. The disadvantage of this method is that if you use this function inside another function, it will only use the value A. For example: length(test(x,y,z)) will simply indicate the length of A.

+2
source share
  a = cell{3, 1}; [a{:}] = test(x, y, z); A = a{1}; B = a{2}; C = a{3}; 
+1
source share

MATLAB will automatically output variables / expressions that do not end with ';' .

So, if you just need to display all of these values, the easiest way would be:

 function [ A, B, C ] = test(x, y, z) A=2*x % no ';' will print A value automatically B=2*y % no ';' will print B value automatically C=2*z % no ';' will print C value automatically end 
0
source share

All Articles