How do I plot the output of a for loop?
1 view (last 30 days)
Show older comments
I have a code that computes the difference between the exponential function in matlab and an approximation of it using the Taylor expansion. I have also computed how many terms of the Taylor expansion are needed to make the expansion a particular degree of accuracy. However, I also want to plot the error at each point as a function of how many terms have been used in the Taylor expansion. I can get my code to give a plot but the plot is incorrect and I'm unsure what's going wrong. The codes I have written so far are
x=2;
expapprox=0;
prompt = 'How many terms in the expansion?'
for i=0:input(prompt)
expapprox=expapprox+x^i/factorial(i);
end
error=abs(expapprox-exp(x))
clear;
n=0;
x=2;
expapprox=0;
while abs(expapprox-exp(x))>=0.001
expapprox=expapprox+x^n/factorial(n);
n=n+1;
end
n
clear;
x=2;
expapprox=0;
expapproxarray=zeros(1,12);
for j=1:length(expapproxarray)
for i=0:12
expapprox=expapprox+x^i/factorial(i);
error=abs(expapprox-exp(x))
expapproxarray(j)=error
end
end
plot(expapproxarray)
The first two sections of code are working but the last one isn't outputting what I want. What is the problem here?
0 Comments
Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!