Skipping outputs with anonymous function in MATLAB

久未见 提交于 2019-11-26 14:28:19

问题


Say I want to create an anonymous function from a m-file-function that returns two outputs. Is it possible to set up the anonymous function such that it only returns the second output from the m-file-function?

Example: ttest2 returns two outputs, t/f and a probability. If I want to use the t-test with cellfun, I might only be interested in collecting the probabilities, i.e. I'd like to write something like this

probabilities = cellfun(@(u,v)ttest2(u,v)%take only second output%,cellArray1,cellArray2)

回答1:


There's no way I know of within the expression of the anonymous function to have it select which output to return from a function with multiple possible output arguments. However, you can return multiple outputs when you evaluate the anonymous function. Here's an example using the function MAX:

>> data = [1 3 2 5 4];  %# Sample data
>> fcn = @(x) max(x);   %# An anonymous function with multiple possible outputs
>> [maxValue,maxIndex] = fcn(data)  %# Get two outputs when evaluating fcn

maxValue =

     5         %# The maximum value (output 1 from max)


maxIndex =

     4         %# The index of the maximum value (output 2 from max)

Also, the best way to handle the specific example you give above is to actually just use the function handle @ttest2 as the input to CELLFUN, then get the multiple outputs from CELLFUN itself:

[junk,probabilities] = cellfun(@ttest2,cellArray1,cellArray2);

On newer versions of MATLAB, you can replace the variable junk with ~ to ignore the first output argument.




回答2:


One way to do this is to define the function:

function varargout = getOutput(func,outputNo,varargin)
    varargout = cell(max(outputNo),1);
    [varargout{:}] = func(varargin{:});
    varargout = varargout(outputNo);
end

and then getOutput(@ttest2,2,u,v) gives only the p-value.

To use it in a cellfun you would need to run:

probabilities = cellfun(@(u,v)getOutput(@ttest2,2,u,v)...

This eliminates the need to write a wrapper every time, but then you have to make sure this function is always in the path.



来源:https://stackoverflow.com/questions/3096281/skipping-outputs-with-anonymous-function-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!