Hey all,
I'm trying to write a general form to compute the partial sum of e^x. So far I've gotten a function that spits out the value of the nth term, but not the sum of that term and all the terms before it. (Ex, if M is 2, the computer gives me 0.5 as the output, but it should be 1+1+0.5 = 2.5 for terms n=0, n=1, and n=2.).
The problem definitely has to do with the summation line-- how do I fix that? Thanks!
function y = Pset0_P5_fxn(x,M)
x = 1; M = 2;
for n = 0:M
a = ((x.^n)./(factorial(n)))
y = sum(a)
end
end
end
EDIT: The function seems to work fine, but won't plot-- for all x values, the y value is the same (whatever the output is on the last iteration). How can I store the output at each iteration in a vector?

 채택된 답변

James Tursa
James Tursa 2015년 2월 5일
편집: James Tursa 2015년 2월 5일

1 개 추천

You replace the "a" variable with each iteration, so only the last iteration is present when you do "sum(a)". So either make "a" a vector (if you want to save the intermediate terms), or just sum as you go. E.g.,
Make "a" a vector:
function y = Pset0_P5_fxn(x,M)
x = 1; M = 2; % test values
for n = 0:M
a(n+1) = ((x.^n)./(factorial(n))); % Note the added (n+1) subscript
end
y = sum(a);
end
Sum as you go:
function y = Pset0_P5_fxn(x,M)
x = 1; M = 2; % test values
y = 0; % Initialize y
for n = 0:M
a = ((x.^n)./(factorial(n)));
y = y + a;
end
end

댓글 수: 1

CLow
CLow 2015년 2월 5일
Ah-ha, thank you! I figured there was something up since I wasn't getting a vector out in the workspace.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2015년 2월 5일

편집:

2015년 2월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by