How can I take the value from an equation and plug it back into the same equation? (Newton-Raphson)
7 views (last 30 days)
Show older comments
I'm trying to implement a Newton-Raphson function into my script. The code I've created so far is;
function [ALI] = down(A, B, C, D, E, n)
A = 0.012;
B = 0.04;
C =0.06;
D = sqrt(A)/2;
n =20
for i = 1:n
E = D - F(D)/F'(D)
ALI = D-E;
end
end
The equation for E has been edited into a simpler form of the newton-raphson equation; the equation is extremely long and includes the variables A, B, & C too. I want to perform equation E in a loop, in which the value from each iteration is placed back into itself, until D minus E is within the required tolerance. However, the way I've written the function means that it just repeats the same equation over and over and I'm not sure how to change this, please could someone help?
Also, variables A, B, C and D depend on other variables, which are calculated earlier in the script.. is there a way in which I can define the variables in the function so that they take the values already calculated in the script? I'm currently having to use a caluclator for the values and then plugging them into the function. This will be a major problem later when im trying to performs loops etc. Thank you.
0 Comments
Accepted Answer
DGM
on 11 Apr 2021
Edited: DGM
on 11 Apr 2021
Something like this:
function D = down(A, B, C, D, maxiter, tol)
% things that are in the argument list don't get rewritten
% function parameters
% A, B, C
% initial condition
% D
% process parameters
% maxiter, tol
stepsize=1;
iter=1;
while stepsize > tol
E = D - F(D)/Fprime(D); % this estimate
stepsize = abs(D-E);
D = E; % is the next point to evaluate at
iter = iter+1;
% just in case we don't converge
if iter > maxiter
break;
end
end
end
If the parameters and intial conditions are input arguments that depend on external variables, why not just precalculate them before passing them to the function?
4 Comments
More Answers (1)
Jan
on 11 Apr 2021
Replace
E = D - F(D)/F'(D)
by
D = D - F(D)/F'(D)
For the 2nd part: You have defined the function with inputs:
function [ALI] = down(A, B, C, D, E, n)
but A,B,C,D are overwritten directly. E does not seem to be an input at all, but a locally used variable.
If you want to use the inputs, define them outside and provide them as inputs when you call your funcion:
function main
A = 0.012;
B = 0.04;
C = 0.06;
D = sqrt(A) / 2;
n = 20;
ALI = down(A, B, C, D, n)
end
function ALI = down(A, B, C, D, n)
for i = 1:n
Dold = D;
D = D - F(D)/F'(D)
ALI = D - Dold;
end
end
3 Comments
Jan
on 11 Apr 2021
You re-define D with the initial value in each iteration:
for i = 1:n
D = sqrt(A)/2;
...
Move the line "D = sqrt(A)/2;" before the loop - exactly as in the FORTRAN code.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!