How do I plot my code? I got Blank Graph

4 views (last 30 days)
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

Accepted Answer

Geoff Hayes
Geoff Hayes on 14 Apr 2019
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 Comments
hgrlk
hgrlk on 14 Apr 2019
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..
Geoff Hayes
Geoff Hayes on 15 Apr 2019
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.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!