MATLAB中N个函数句柄的求和 [英] Summation of N function handles in MATLAB

查看:1563
本文介绍了MATLAB中N个函数句柄的求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MATLAB中具有N函数,可以在for循环中使用strcatnum2streval定义它们.因此,无需手动定义即可定义N函数.让N=4并给出如下:

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));

在这里我可以手工完成,因为我知道N=4.但是,总的来说,我永远不知道我将拥有多少功能.在所有情况下,我都无法编写新功能.

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.

有什么办法可以自动执行此操作?我的意思是,如果我给N=6,我希望看到MATLAB给我:

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));

每当我给出N=2时,我都必须具有函数f,其定义如下:

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

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

我们如何做到这一点?

推荐答案

首先,您应该阅读

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.

因此,您无需定义函数f1f2f3,... fN,而是定义函数f{1}f{2}f{3},... f{N}.也就是说,f是一个单元格数组,其中的每个元素都是一个匿名函数(或任何其他函数句柄).

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).

例如,代替

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

你做

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

有了这些更改,我们可以轻松回答问题.现在,我们可以编写一个输出f中的函数总和的函数:

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

您可以将其放置在名为sum_of_functions.m的文件中,也可以将其放置在功能文件或脚本文件的末尾,没关系.现在,在您的代码中,当您要评估y = f1(x) + f2(x) + f3(x)...时,您写的是y = sum_of_functions(f,x).

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).

这篇关于MATLAB中N个函数句柄的求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆