这是我试过的:
f = @(x) 0;
for i = 1:n
f = @(x) f(x) + x^i;
end
Run Code Online (Sandbox Code Playgroud)
当我通过输入一些值来测试它时,似乎做了正确的事情.
但是在打印时f我得到了这个输出f = @(x) f(x) + x^i
编辑:那么当我打印时,如何得到我想要看到的输出,其中所有的加数都在函数句柄中f.
您可以使用符号函数(symfun)来执行您想要的操作:
% create symbolic variable
syms x
% define order of polynom
n = 3;
% create polynom
fs(x) = 0*x;
for i = 1:n
fs(x) = fs(x) + x.^i;
end
% convert symbolic function to function handle
f = matlabFunction(fs)
Run Code Online (Sandbox Code Playgroud)
结果是:
f =
@(x)x+x.^2+x.^3
Run Code Online (Sandbox Code Playgroud)
编辑:这是一种不使用符号数学工具箱的方法:
% define order of polynom
n = 3;
% create polynom as string
fstring = '0';
for i = 1:n
fstring = [fstring, '+x.^',num2str(i)];
end
f = str2func(['@(x)',fstring]);
Run Code Online (Sandbox Code Playgroud)
结果是:
f =
@(x)0+x.^1+x.^2+x.^3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
309 次 |
| 最近记录: |