return multiple output variables from Matlab function

后端 未结 4 1328
既然无缘
既然无缘 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条回答
  •  梦毁少年i
    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.

提交回复
热议问题