我写了这个函数:
function [sum] = func(a,b)
sum = 0;
for i = 0:b
sum = sum + ((a.^i)/(factorial(i)));
end
在控制台中,我给出的命令是:
>> x = [10:10:100]
x =
10 20 30 40 50 60 70 80 90 100
我得到了:
>> y = func(10,x)
y =
1.2842e+04
为什么我没有收到矢量?为什么数字这么大(它应该接近10)? 任何帮助将不胜感激!
答案 0 :(得分:2)
好吧,如果你不用sum
索引i
,你就会返回一个值。
尝试改为:
function [sum] = func(a,b)
% Pre-allocate sum at the right size
sum = NaN(1,b+1);
% Compute
for i = 0:b
sum(i+1) = sum(i+1) + ((a.^i)/(factorial(i)));
end
最佳,
答案 1 :(得分:1)
f = @(x,i) (x.^i)./factorial(i)
r=f(10,0:50); %50 terms in taylor series more than enough for good approx.
cumsum(r)
1.0e+04 *
0.0001
0.0011
0.0061
0.0228
....
2.202646579479054
2.202646579480280
验证
>> exp(10)
2.202646579480672e+04