return multiple output variables from Matlab function

后端 未结 4 1303
既然无缘
既然无缘 2021-01-02 07:11

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 on

相关标签:
4条回答
  • 2021-01-02 07:49

    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.

    0 讨论(0)
  • 2021-01-02 07:51

    MATLAB will automatically ouput the variables/expressions those are not end with a ';'.

    So if you just need to display all these values, the simplest way will be:

    function [ A, B, C ] = test(x, y, z)
        A=2*x    % no ';' will print A's value automatically
        B=2*y    % no ';' will print B's value automatically
        C=2*z    % no ';' will print C's value automatically
    end
    
    0 讨论(0)
  • 2021-01-02 07:52

    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.

    0 讨论(0)
  • 2021-01-02 07:57

    Matlab function outputs are in cell format, so you can define a cell data with the size same as the function output and use it as a single variable to store all the outputs in a more structured way :)

    a = cell{3, 1};
    [a{:}] = test(x, y, z);
    A = a{1};
    B = a{2};
    C = a{3}; 
    
    0 讨论(0)
提交回复
热议问题