Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skipping outputs with anonymous function in MATLAB

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)
like image 711
Jonas Avatar asked Jun 22 '10 19:06

Jonas


People also ask

Can anonymous functions have multiple outputs MATLAB?

but anonymous functions are not allowed more than one outputs.

How do you skip output in MATLAB?

To ignore function outputs in any position in the argument list, use the tilde operator. For example, ignore the first output using a tilde. [~,name,ext] = fileparts(helpFile); You can ignore any number of function outputs using the tilde operator.

Can anonymous functions have multiple outputs?

What Are Anonymous Functions? An anonymous function is a function that is not stored in a program file, but is associated with a variable whose data type is function_handle . Anonymous functions can accept multiple inputs and return one output. They can contain only a single executable statement.

Can an anonymous function be assigned to a variable?

An anonymous function in javascript is not accessible after its initial creation. Therefore, we need to assign it to a variable, so that we can use its value later. They are always invoked (called) using the variable name. Also, we create anonymous functions in JavaScript, where we want to use functions as values.


1 Answers

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.

like image 115
gnovice Avatar answered Sep 21 '22 08:09

gnovice