필터 지우기
필터 지우기

My graph for a while loop approximation is blank!

조회 수: 1 (최근 30일)
Thomas MacDowell
Thomas MacDowell 2018년 7월 16일
편집: Stephen23 2018년 7월 17일
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
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
Stephen23
Stephen23 2018년 7월 17일
편집: Stephen23 2018년 7월 17일
+1 nice clear explanation. Better would be to not use any loop.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Graph and Network Algorithms에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by