MATLAB Answers

Newton Raphson Method in a for loop

44 views (last 30 days)
Aaron Fredrick
Aaron Fredrick on 22 Dec 2020
Answered: James Tursa on 22 Dec 2020
Hey guys, I have been given the task to find the x value with respect to minimum cost using Newton Rphson method, where cost is a function of x (fx = cost according the code). And also according the given task and the below code, value of D for a set of values of x is constant and the x value for minimum cost has to be found for every D value,
% data %
L = 120;
C_S1 = 2.5e+06;
C_O1 = 2e+06;
% creating an array of 100 elements from 0 to 120 %
x = linspace(0,120,100);
% creating an array for D %
D = 1:80;
% preallocation for optimal distance & cost %
Optimal_distance = zeros(1,length(D));
Cost = zeros(1,length(D));
% Newton-Raphson's Method %
% initial guess %
x0 = 110;
for j = length(D):-1:1
% function value %
fx = @(x) (C_S1)*sqrt(D(j)^(2)+x.^(2))+(C_O1)*(L-x);
f = fx(x0);
% 1st derivative value %
gx = @(x) ((C_S1)*x./sqrt(x.^(2)+D(j)^2))-(C_O1);
g = gx(x0);
Precision = 0.01;
while abs(g) > Precision
% Newton-Raphson's formula %
xr = x0 - f/g;
% new function value %
f= fx(xr);
% new 1st derivative value %
g= gx(xr);
% initial guess for the next D value %
x0 = xr;
% storing values in preallocated vectors %
Cost(j) = f;
Optimal_distance(j) = xr;
figure(4) %figure 4
% plotting optimal value of x against D %
plot(Optimal_distance, D, '-k')
xlabel('D (km)')
ylabel('Optimal value of x (km)')
% plotting minimum cost against D %
plot(Cost, D, '-k')
xlabel('D (km)')
ylabel('Minimum cost ($)')
But my code doesnt finish its run where as the problem was in the part where while loops starts running, but i dont know hot overcome this error or peoblem...

Answers (2)

Asad (Mehrzad)  Khoddam
Asad (Mehrzad) Khoddam on 22 Dec 2020
Newton method is originally for root finding. If you want to use it for optimization, the derivative of the function should be zero. So you need to have anothe derivative h(x) = g'(x) , then use x= x-g/h

James Tursa
James Tursa on 22 Dec 2020
You don't have the Newton-Raphson method coded correctly. You need to update the x value you use for the delta within the loop itself. E.g., something like this if we stay with your xr variable:
xr = x0; % <-- added xr initialization
while abs(g) > Precision
% Newton-Raphson's formula %
xr = xr - f/g; % <-- changed x0 to xr
% new function value %
f= fx(xr);
% new 1st derivative value %
g= gx(xr);

Community Treasure Hunt

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

Start Hunting!