return multiple output variables from Matlab function

后端 未结 4 1305
既然无缘
既然无缘 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.

提交回复
热议问题