Adding values in a for loop
2 次查看(过去 30 天)
显示 更早的评论
Is there a way to add the values that the for loop spits out? I'm trying to make a function for the taylor series.
for i = 0:n
syms c
d=inline(diff(cosh(c),c,i+1));
g = ((d(0)* x^i )/(factorial(i)))
end
n and x are values that I put in. The output values are the same ones that I am looking for but the only problem I have is adding them together.
0 个评论
回答(2 个)
Sven
2013-2-13
Hi Andy,
I'm not entirely clear what you mean by "output", but I'll presume that you mean the value assigned to the g variable. In that case, all you need to do is to store your g variable at each loop iteration as follows:
g_set = zeros(1,n+1); % n+1 because you start your loop at "0"
for i = 0:n
syms c
d=inline(diff(cosh(c),c,i+1));
g = ((d(0)* x^i )/(factorial(i)))
g_set(i+1) = g;
end
Now, you've recorded the value of g at each iteration. You can simply add these up by:
g_total = sum(g_set)
Does that work for you?
Thanks, Sven.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!