How do I plot the output of a for loop?

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?

Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Asked:

JJH
on 3 Nov 2018

Community Treasure Hunt

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

Start Hunting!