How do I plot my code? I got Blank Graph
조회 수: 3 (최근 30일)
이전 댓글 표시
Hello,
I want to plot my code. It's newton-raphson method code. But I musn't change the while loop. In the question it is given that "use while and if statement".
When I write the plot, Matlab gives me a blank graph. So I exclude the " plot" when I'm sharing the code with you.
NOTE : . I want 2 graphs, one is f(x) versus i and one is x versus i. Also how can I write a function for the circle mark for each data point in the function?
( I use Matlab R2015a )
Thank You.!!
clc
clear all
close all
fprintf('%10s %10s %10s %10s %10s\n','i','xi','f(xi)','diff_f(xi)','|Ea|')
Ea = 100;
m = 0 ;
x = 0;
while abs(Ea) > 10^(-3)
if m <= 50
f = @(x) x^3 - x - 3 ;
diff = @(x) 3*(x^2) - 1 ;
xnew = x - (f(x) / diff(x));
Ea = (((xnew-x)/xnew)*100);
fprintf('%10.4f %10.4f %10.4f %10.4f %10.4f\n',m,x,f(x),diff(x),abs(Ea))
x = xnew;
else
break
end
m = m+1;
end
댓글 수: 0
채택된 답변
Geoff Hayes
2019년 4월 14일
hgrlk - store each value of x from each iteration of your loop. Then, when the loop concludes, you can plot the data. Perhaps somethig like
Ea = 100;
maxIterations = 50;
m = 1;
x = zeros(maxIterations,1);
x(m) = 12;
f = @(x) x.^3 - x - 3 ;
diff = @(x) 3*(x.^2) - 1 ;
while abs(Ea) > 10^(-3) && m < maxIterations
xnew = x(m) - (f(x(m)) / diff(x(m)));
Ea = (((xnew-x(m))/xnew)*100);
fprintf('%d %10.4f %10.4f %10.4f %10.4f\n',m,x(m),f(x(m)),diff(x(m)),abs(Ea));
m = m + 1;
x(m) = xnew;
end
x = x(1:m);
figure;
plot(x);
figure;
plot(f(x));
Note how we combine the two conditions that you have - that for the error and that for the maximum number of iterations. The f and diff are defined outside of the while loop since we can then have access to f when we plot (once complete). On each iteration of the loop, we store the new estimate in an array so that we can plot all values of x and f(x). See plot LineSpec properties for details on how to add colour, style, and markers to your plot.
댓글 수: 2
Geoff Hayes
2019년 4월 15일
You can put the if back then if that is what you need (same as you originally had). As for nothing in the graph, I was able to see the results plotted in each figure (using the code I posted).
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!