Adding values in a for loop

2 次查看(过去 30 天)
Andy
Andy 2013-2-13
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.

回答(2 个)

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

Andy
Andy 2013-2-19
Thank you for answering. I was trying to make a matrix and use that matrix for a taylor series approximation. I was unable to explain that I was looking for a way to make a matrix because I didn't know there was a name for it.

类别

Help CenterFile Exchange 中查找有关 Mathematics 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by