MATLAB: How to plot this data set like this image

datafor looploopplotplots

So I have a function:
function [ xs ] = myExpFunction(x)
xs=zeros(1,length(x));
xl=zeros(51,length(x)); %preallocation of the storage
for n= 0:50
xt = ((x.^n)/factorial(n));
if xt(xt <0.01)
xt(xt <0.01)=0;
end
xl(n+1,:) = xt
end
for ii = 1:length(x)
xs(ii)=sum(xl(:,ii)) ; %calculate the sum of the iteration results
end
end
And at this line:
xl(n+1,:) = xt
@ x= [1 2 3 4 5]
Gives out:
xl =
1.0000 1.0000 1.0000 1.0000 1.0000
1.0000 2.0000 3.0000 4.0000 5.0000
0.5000 2.0000 4.5000 8.0000 12.5000
0.1667 1.3333 4.5000 10.6667 20.8333
0.0417 0.6667 3.3750 10.6667 26.0417
0 0.2667 2.0250 8.5333 26.0417
0 0.0889 1.0125 5.6889 21.7014
0 0.0254 0.4339 3.2508 15.5010
0 0 0.1627 1.6254 9.6881
0 0 0.0542 0.7224 5.3823
0 0 0.0163 0.2890 2.6911
0 0 0 0.1051 1.2232
0 0 0 0.0350 0.5097
0 0 0 0.0108 0.1960
0 0 0 0 0.0700
0 0 0 0 0.0233
My task is to create some code in the function to add up the numbers per iteration and plot them against x. i.e. at n=0, there will just be a line through y=1, but at n=1, y=[2 3 4 5 6] where the 1st row adds to the 2nd row. How do I do this!? Please help 🙁
%

Best Answer

Japoe25 - if you want your output to look like something similar to the images, the first thing that you should do is to get your x to reflect the x-axis interval shown in the above images. So rather than using
x = [1 2 3 4 5];
use
x = linspace(-2,2,100);
which will create an array of 100 linearly spaced elements from -2 to +2. The next thing that you may want to do is to make n an input parameter. So change your function signature to
function [ xs ] = myExpFunction(x,n)
and the for loop indexing to
for k= 0:n
xt = ((x.^k)/factorial(k));
if xt(xt <0.01)
xt(xt <0.01)=0;
end
xl(k+1,:) = xt;
end
Now, to try the case for n equals to zero, you would call your function as
x = linspace(-2,2,100);
y = myExpFunction(x,0);
which you can plot as
close all;
plot(x,exp(x),'b',x,y,'r');
you will observe a result that is near identical to the first image. Trying the same for n equals one will produce something slightly different for the domain values of [-2,0] because of the condition in your code to zero all elements that are less than 0.01 (why does this condition exist?). If you remove this condition (which is unnecessary and harmful due to the approximation that it introduces), then you should get the correct results.