Asked by hgrlk
on 14 Apr 2019

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

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;

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.

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
on 15 Apr 2019

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.