Summation of N function handles in MATLAB

早过忘川 提交于 2020-01-14 17:39:34

问题


I have N functions in MATLAB and I can define them using strcat, num2str and eval in a for loop. So without defining by hand I am able to define N functions. Let N=4 and let them be given as follows:

f1=@(x) a1*x+1;
f2=@(x) a2*x+1;
f3=@(x) a3*x+1;
f4=@(x) a4*x+1;

Now I add these four functions and I can do this by hand as follows:

f=@(x)(f1(x)+f2(x)+f3(x)+f4(x));

Here I can do it by hand because I know that N=4. However, in general I never know how many functions I will have. For all cases I cannot write a new function.

Is there any way to do this automatically? I mean if I give N=6 I am expecting to see MATLAB giving me this:

f=@(x)(f1(x)+f2(x)+f3(x)+f4(x)+f5(x)+f6(x));

Whenever I give N=2 then I must have the function f, defined as follows:

f=@(x)(f1(x)+f2(x));

How can we do this?


回答1:


First of all, you should read this answer that gives a series of reasons to avoid the use of eval. There are very few occasions where eval is necessary, in all other cases it just complicates things. In this case, you use to dynamically generate variable names, which is considered a very bad practice. As detailed in the linked answer and in further writings linked in that answer, dynamic variable names make the code harder to read, harder to maintain, and slower to execute in MATLAB.

So, instead of defining functions f1, f2, f3, ... fN, what you do is define functions f{1}, f{2}, f{3}, ... f{N}. That is, f is a cell array where each element is an anonymous function (or any other function handle).

For example, instead of

f1=@(x) a1*x+1;
f2=@(x) a2*x+1;
f3=@(x) a3*x+1;
f4=@(x) a4*x+1;

you do

N = 4;
a = [4.5, 3.4, 7.1, 2.1];
f = cell(N,1);
for ii=1:N
   f{ii} = @(x) a(ii) * x + 1;
end

With these changes, we can easily answer the question. We can now write a function that outputs the sum of the functions in f:

function y = sum_of_functions(f,x)
   y = 0;
   for ii=1:numel(f)
      y = y + f{ii}(x);
   end
end

You can put this in a file called sum_of_functions.m, or you can put it at the end of your function file or script file, it doesn't matter. Now, in your code, when you want to evaluate y = f1(x) + f2(x) + f3(x)..., what you write is y = sum_of_functions(f,x).



来源:https://stackoverflow.com/questions/58143196/summation-of-n-function-handles-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!