MATLAB: Is the for loop not iterating in the way I want

for loop

I have a piece of code
clear;
x=2;
expapprox=0;
expapproxarray=zeros(1,12);
for i=0:12
expapprox=expapprox+x^i/factorial(i);
error=abs(expapprox-exp(x))
for j=1:size(expapproxarray)
expapproxarray(j)=error
end
end
plot(expapproxarray)
that compares the exponential function to an approximation of that function using the Taylor series. I want to plot the error found between the two functions for an increasing number of terms in the Taylor expansion. I thought this could be done using the code above but there is a problem with how the second loop works. I think the problem is that the full iteration of the second loop is being done within the first loop but changing the order of the loops gives another wrong answer. How can I get the value of error for each value of I to be outputted into some array that I have called expapproxarray that can then be plotted as a function of i?

Best Answer

N = 2; % the value to use.
% Approximation:
X1 = 1:12; % the number of terms.
Y1 = nan(size(X1));
for k = X1
T = 0:k-1;
Y1(k) = sum(N.^T./factorial(T));
end
% Inbuilt function:
X2 = X1([1,end]);
Y2 = exp([N,N]);
% Plot:
plot(X1,Y1,'*',X2,Y2,'-')
xlabel('Number of terms')
ylabel('Output value')
Plots this:
You can plot the error simply by subtracting exp(N):
plot(X1,Y1-exp(N))