1

I'm trying to automatically create a function handle that is a sum of function handles. When I tried to do this manually, it worked:

f1 = @(x) x(1);  
f2 = @(x) x(2);   
f3 = @(x) x(3);  
f = @(x) f1(x)+f2(x)+f3(x);  

But when I tried to do this automatically (using a for-loop):

aux = {f1,f2,f3};  
f = @(x) 0;
for i=1:3    
   f = @(x) f(x) + cell2mat(aux(i));
end

I get the following error:

Undefined operator '+' for input arguments of type 'function_handle'.

My goal is to use this function handle with fmincon function.

So an alternative solution would also help.

StackedQ
  • 3,999
  • 1
  • 27
  • 41

1 Answers1

0

In the first case you are adding the result of the function calls, which works fine. In the second case you are trying to add function handles, which isn't implemented.

The work around would be to use cellfun to evaluate your functions then add the results together:

f = @(x)sum(cellfun(@(c)feval(c,x),aux));

The above assumes that your functions all return a scalar numeric. If that's not the case in your real application then you'll need to modify the use of cellfun appropriately.

Phil Goddard
  • 10,571
  • 1
  • 16
  • 28
  • Thanks, but it doesn't help. As Cris Luengo said, I need a function handle not a evaluation of the sum. – Felipe Carvalho May 21 '18 at 13:50
  • It is a function handle. Can you give an example where the above solution doesn't give the same result as your manual _it worked_ solution? – Phil Goddard May 21 '18 at 14:15
  • I agree. It will give the same result, but I don't need the result. I need the function handle to deal with fmincon function. And, more especifically, I need a automatic way to create this function handle. – Felipe Carvalho May 21 '18 at 15:23