How to directly pass multiple outputs of a function to another?

后端 未结 1 704
轮回少年
轮回少年 2020-12-12 06:08

Let me elaborate with examples: We know how to easily combine functions with a single output:

a = sin(sqrt(8));

Now consid

相关标签:
1条回答
  • 2020-12-12 06:19

    To answer the question in the title: Using the following function, it is possible to redirect multiple outputs of a function to another:

    function varargout = redirect(source, destination, n_output_source, which_redirect_from_source, varargin)
    %(redirect(source, destination, n_output_source, which_redirect_from_source,....)
    %redirect output of a function (source) to input of another function(destination)
    % source: function pointer
    % destination: function pointer
    % n_output_source: number of outputs of source function (to select best overload function)
    % which_redirect_from_source: indices of outputs to be redirected
    % varargin arguments to source function
        output = cell(1, n_output_source);
        [output{:}] = source(varargin{:});
        varargout = cell(1, max(nargout,1));
        [varargout{:}] = destination(output{which_redirect_from_source});
    end
    

    And now we can apply it to the example:

    [~,R] = redirect(@meshgrid,@cart2pol, 2, [1, 2], -2:2, -2:2)
    

    Here, source function has 2 outputs and we want to redirect outputs 1 and 2 from source to destination. -2:2 is the input argument of the source function.


    Other way to deal with the mentioned example: If you can use GNU Octave, with bsxfun and nthargout this is your solution:

    R = bsxfun(@(a,b) nthargout(2, @cart2pol,a,b),(-2:2)',(-2:2))
    

    in Matlab a possible solution is:

    [~, R] = cart2pol(meshgrid(-2:2), transpose(meshgrid(-2:2)))
    

    or

    function R = cart2pol2(m)
        [~,R] = cart2pol(m,m')
    end
    
    cart2pol2(meshgrid(-2:2, -2:2))
    
    0 讨论(0)
提交回复
热议问题