My graph for a while loop approximation is blank!
1 回表示 (過去 30 日間)
古いコメントを表示
I have tried to find the solution to this but can't seem to figure it out. I know that my values are scalar and that's why they are coming out blank, but I don't know how to vector them in order to graph them. This is the code I am trying to graph. I also need to have the graph compare my e^x approximation with the actual e^x value. This code is being run at x=3
figure
grid on
hold on
xsize = 0:2;
n = 0;
ex = 0;
while n < 3
ex = ex + x.^n/factorial(n);
n = n + 1;
plot(xsize,ex,xsize,exp(x))
end
EDIT: This graph is meant to be shown as a function of n, which is why 'xsize' = 0:2 because I am only graphing a 3 term approximation
回答 (1 件)
Tejas Jayashankar
2018 年 7 月 16 日
Hi Thomas,
You should not be plotting the graph within every iteration of the loop. As you mentioned, you need a vector of values to plot the approximation to e^3. So if you make ex a vector and accumulate the various terms of the Taylor series expansion in each iteration, you can plot out your results at the end as follows:
x = 3;
figure;
hold on
xsize = 0:500;
n = 0;
ex = 0;
while n < xsize(end)
ex = [ex; x.^n/factorial(n)];
n = n + 1;
end
plot(xsize, cumsum(ex), [0 xsize(end)], [exp(3) exp(3)])
ylim([0 30])
In the while loop I am accumulating each term of the taylor series expansion into a vector. So the vector would be
[0 1 x x^2/2! x^3/3! ...]
for some general value x, which is 3 in your case. Outside the while loop, when you want to plot the approximation for each value of n, just perform a cumulative sum using the cumsum function. To plot the actual of e^3 you need to specify the starting and ending coordinates of the line in the plot function.
1 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!