Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

summing functions handles in matlab

Hi
I am trying to sum two function handles, but it doesn't work. for example:

y1=@(x)(x*x);
y2=@(x)(x*x+3*x);
y3=y1+y2

The error I receive is "??? Undefined function or method 'plus' for input arguments of type 'function_handle'."

This is just a small example, in reality I actually need to iteratively sum about 500 functions that are dependent on each other.

EDIT
The solution by Clement J. indeed works but I couldn't manage to generalize this into a loop and ran into a problem. I have the function s=@(x,y,z)((1-exp(-x*y)-z)*exp(-x*y)); And I have a vector v that contains 536 data points and another vector w that also contains 536 data points. My goal is to sum up s(v(i),y,w(i)) for i=1...536 Thus getting one function in the variable y which is the sum of 536 functions. The syntax I tried in order to do this is:

sum=@(y)(s(v(1),y,z2(1))); 
for i=2:536 
  sum=@(y)(sum+s(v(i),y,z2(i))) 
end
like image 955
user552231 Avatar asked Jan 16 '11 09:01

user552231


1 Answers

The solution proposed by Fyodor Soikin works.

>> y3=@(x)(y1(x) + y2(x))
y3 =
@(x) (y1 (x) + y2 (x))

If you want to do it on multiple functions you can use intermediate variables :

>> f1 = y1;
>> f2 = y2;
>> y3=@(x)(f1(x) + f2(x))

EDIT after the comment: I'm not sure to understand the problem. Can you define your vectors v and w like that outside the function :

v = [5 4]; % your 536 data
w = [4 5];
y = 8;
s=@(y)((1-exp(-v*y)-w).*exp(-v*y))
s_sum = sum(s(y))

Note the dot in the multiplication to do it element-wise.

like image 144
Clement J. Avatar answered Sep 19 '22 11:09

Clement J.