How do I plot this data set like this image?
1 次查看(过去 30 天)
显示 更早的评论
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 :(
%
0 个评论
采纳的回答
Geoff Hayes
2015-4-11
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.
2 个评论
Geoff Hayes
2015-4-11
Including the condition creates the image that you have posted above. Since your code doesn't actually terminate if the values of xt fall below 0.01 then (for fun) just remove it and try again...I think that you will get the plot/figure that you are expecting.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!