MATLAB Answers

## How to convert a cell array containing various inline functions to a unique inline function?

Asked by Dyecks da Rocha Fialho

### Dyecks da Rocha Fialho (view profile)

on 5 Jun 2019
Latest activity Edited by TADA

### TADA (view profile)

on 5 Jun 2019
Accepted Answer by Stephen Cobeldick

### Stephen Cobeldick (view profile)

I need to use the fminimax function and the input has to be necessarily a single inline function. But I need several equations in this function. And I'm going to add them one by one through a for loop in a cell.
I need to convert this:
cell =
1×3 cell array
{@(x)(a(1,1)-x)^2} {@(x)(a(2,2)-x)^2} {@(x)(a(3,3)-x)^2}
For this:
func =
function_handle with value:
@(x)[(a(1,1)-x)^2;(a(2,2)-x)^2;(a(3,3)-x)^2]

#### 0 Comments

Sign in to comment.

R2019a

## 2 Answers ### Stephen Cobeldick (view profile)

Answer by Stephen Cobeldick

### Stephen Cobeldick (view profile)

on 5 Jun 2019
Edited by Stephen Cobeldick

### Stephen Cobeldick (view profile)

on 5 Jun 2019
Accepted Answer

You could hide the loop inside cellfun:
>> a = rand(3,3);
>> C = {@(x)(a(1,1)-x)^2,@(x)(a(2,2)-x)^2,@(x)(a(3,3)-x)^2};
>> F = @(x)cellfun(@(f)f(x),C(:));
>> F(1.2)
ans =
0.40767
0.39542
1.26850

#### 0 Comments

Sign in to comment.

Answer by TADA

on 5 Jun 2019
Edited by TADA

### TADA (view profile)

on 5 Jun 2019

You can generate a function handle which will execute all the handles in a cell array using closures:
a = magic(3);
myFunctions = [{@(x)(a(1,1)-x)^2} {@(x)(a(2,2)-x)^2} {@(x)(a(3,3)-x)^2}];
aggregatedFunctionHandle = genFunHandle(myFunctions);
disp(aggregatedFunctionHandle(10));
function foo = genFunHandle(handles)
function y = func(x)
y = cellfun(@(fh) fh(x), reshape(handles, numel(handles), 1));
end
foo = @func;
end
output:
6724
4900
6084
but if your functions are always of that format: @(x)(a(i,i)-x)^2
do this instead:
f = @(x) (diag(a)-x).^2

TADA

### TADA (view profile)

on 5 Jun 2019
also possible with an inline closure like that:
a = magic(3);
myFunctions = [{@(x)(a(1,1)-x)^2} {@(x)(a(2,2)-x)^2} {@(x)(a(3,3)-x)^2}];
aggregatedFunctionHandle =...
@(x) cellfun(@(fh) fh(x), reshape(myFunctions, numel(myFunctions), 1));

Sign in to comment.