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