MATLAB Answers


How do I plot my code? I got Blank Graph

Asked by hgrlk
on 14 Apr 2019
Latest activity Commented on by Geoff Hayes
on 15 Apr 2019
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.!!
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;
m = m+1;


Sign in to comment.

1 Answer

Answer by Geoff Hayes
on 14 Apr 2019
 Accepted Answer

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;
x = x(1:m);
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.


I understand that solution I guess, but I must use if condition, because it is given in the question. Thats why I wrote while abs(Ea) > 10^(-3) and if m <= 50 in my code.
How can I write that without change the if condition?
when I add plot in my code there is nothing in the graph..
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).

Sign in to comment.