MATLAB: Problem storing variable data in for loop

for loop variable

I am trying to store data for a variable in a for loop and then plot it against something else. I am guessing that the variable is getting overwritten, but can not seem to work a way to do this out. Here is the code:
clc
clear all
x=(-4:.1:4)
y=5*exp(x)
N=input('What value for n?')
b=0*y
for n=1:N
b(n) = b + 5*(x.^n)/factorial(n)
end
e=abs(100*(y-b)/y)
figure(2)
plot (x,e)
figure(3)
plot (x,y, 'r-o')
hold on
plot (x,b)
I added the subscript to the variable b as a way to store it, but I get errors about matrix sizes not matching. Is someone able to point out what is wrong or another solution to the problem?

Best Answer

My speculation is you want
for n = 2:N+1
b(n) = b(n-1) + 5*(x.^(n-1))/factorial(n-1)
end
b = b(2:end);
e = abs(100*(y-b)./y);
but if so then you could replace the loop with
n = 1 : N;
b = cumsum( 5 * x.^n ./ factorial(n) );