How to directly pass multiple function outputs to another?

Let me elaborate on examples:. We know how easy it is to combine functions with one output:

a = sin(sqrt(8)); 

Now consider this code example, which contains two steps to calculate R , with X and Y as intermediate outputs.

 [X, Y] = meshgrid(-2:2, -2:2); [~, R] = cart2pol(X, Y); 

In general, is there a way to combine the two functions and get rid of intermediate results? For example, how can I write something similar to [~, R] = cart2pol(meshgrid(-2:2, -2:2)) , which works the same as the previous code?

Note. What makes my question different from this question is that in my case the external function accepts multiple inputs. Therefore, I cannot and do not want to combine the outputs of the first function into one array of cells. I want them to be transferred to the second function separately.

0
source share
1 answer

To answer the question in the header: Using the following function, you can redirect multiple outputs of the 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 for example:

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

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


Another way to handle this 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 solution is possible:

 [~, 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)) 
+2
source

Source: https://habr.com/ru/post/1259440/


All Articles