Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a cell array of functions to a value

Tags:

matlab

I define a cell array that contains values and functions:

>> A = {1, 2, 3; @(x) x+5, @(x) x+10, 5}

A = 

    [    1]    [     2]    [3]
    @(x)x+5    @(x)x+10    [5]

Does anyone know how to apply this cell array to a value? For instance, when x = 2, the application returns another cell array:

    [ 1]    [     2]    [3]
    [ 7]    [    12]    [5] 
like image 871
SoftTimur Avatar asked Mar 15 '23 11:03

SoftTimur


2 Answers

Define your constants as functions:

A = {@(x)1, @(x)2, @(x)3; @(x) x+5, @(x) x+10, @(x)5}

now use cellfun:

k = 2;
cellfun(@(x)x(k),A)

Also note that if you want to apply multiple k values at once (e.g. k = 1:5) you will need to edit your constant functions in A from this form @(x) n to something like @(x) n*ones(size(x)) and then change the cellfun call to:

cellfun(@(x)x(k),A, 'uni',0)

To answer the question from your comments:

is it possible to refer to other cells in a function in a cell array? For instance, can we define something like A = {@(x)1, @(x)2, the 1st cell + the 2nd cell, @(x)4}?

You define A as follows:

A = {@(x)1, @(x)2, @(x)(A{1}(x)+A{2}(x)), @(x)4}
like image 98
Dan Avatar answered Mar 25 '23 09:03

Dan


Wouldn't it be better to define the cell-array/function thingie like this:

A = @(x) {1, 2, 3; x+5, x+10, 5};

Then you can apply it by simpliy doing

A(2)

Maybe you can even use normal matrices instead of cell array here:

A = @(x) [1, 2, 3; x+5, x+10, 5];
like image 38
Wauzl Avatar answered Mar 25 '23 10:03

Wauzl