开发者

summing functions handles in matlab

开发者 https://www.devze.com 2023-02-04 06:29 出处:网络
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);

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


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.


I think the most succinct solution is given in the comment by Mikhail. I'll flesh it out in more detail...

First, you will want to modify your anonymous function s so that it can operate on vector inputs of the same size as well as scalar inputs (as suggested by Clement J.) by using element-wise arithmetic operators as follows:

s = @(x,y,z) (1-exp(-x.*y)-z).*exp(-x.*y);  %# Note the periods

Then, assuming that you have vectors v and w defined in the given workspace, you can create a new function sy that, for a given scalar value of y, will sum across s evaluated at each set of values in v and w:

sy = @(y) sum(s(v,y,w));

If you want to evaluate this function using an array of values for y, you can add a call to the function ARRAYFUN like so:

sy = @(y) arrayfun(@(yi) sum(s(v,yi,w)),y);

Note that the values for v and w that will be used in the function sy will be fixed to what they were when the function was created. In other words, changing v and w in the workspace will not change the values used by sy. Note also that I didn't name the new anonymous function sum, since there is already a built-in function with that name.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号