Skipping outputs with anonymous function in MATLAB

后端 未结 2 751

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 sec

2条回答
  •  爱一瞬间的悲伤
    2020-12-01 19:12

    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.

提交回复
热议问题