Adding values in a for loop

2 visualizzazioni (ultimi 30 giorni)
Andy
Andy il 13 Feb 2013
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.

Risposte (2)

Sven
Sven il 13 Feb 2013
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 il 19 Feb 2013
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.

Categorie

Scopri di più su Mathematics in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by