Solving Nonlinear Equations Repeatedly
Show older comments
Hallo,
I am new with Matlab, since I need to solve a system of two non-linear equations using the Newton method. I found a code in the Internet and adjusted it and it works, as long as my variables are only consisting of one value. However my variables (A,B,C,D)are actually arrays of about 2000 values (each has the same number of values). So what I need is that Matlab solves the same set of nonlinear equations, each time using a different set of values. In the end I need two arrays for x and y containing the soluations for each set of values.
Thank you for your help.
The code I use:
% Newton Raphson solution of two nonlinear algebraic equations
% set up the iteration
error1 = 1.e8;
xx(1) = Guess1; % initial guesses
xx(2) = Guess2;
iter=0;
itermax=1000.
% begin iteration
while error1>1.e-12
iter=iter+1;
x = xx(1);
y = xx(2);
% calculate the functions
f(1) = x*normcdf((log(x/A)+(C +0.5*y^2))/y) - A * exp(-(C))*normcdf((log(x/A)+(C +0.5*y^2))/y)-y-B;
f(2) =(x/B)*normcdf((log(x/A)+(C +0.5*y^2))/(y*1))*y-(D);
% calculate the Jacobian
J(1,1) = normcdf((log(x/A)+(C +0.5*y^2))/y);
J(1,2) = x*1*(exp((-((log(x/A)+(C +0.5*y^2))/y)^2)/2))/((sqrt(2)*pi*1)*x*y);
J(2,1) = normcdf((log(x/A)+(C +0.5*y^2))/y)*y +(x*1*(exp((-((log(x/A)+(C +0.5*y^2))/y)^2)/2))/((sqrt(2)*pi*1)*x*y));
J(2,2) = x*normcdf((log(x/A)+(C +0.5*y^2))/y)+x*y*(exp((-((log(x/A)+(C +0.5*y^2))/y)^2)/2))/((sqrt(2)*pi*1)*x*y)*((log(x/(A*exp(-(C))))))/(y^2)+0.5;
% solve the linear equations
y = -J\f';
% move the solution, xx(k+1) - xx(k), to xx(k+1)
xx = xx + y';
% calculate norms
error1=sqrt(y(1)*y(1)+y(2)*y(2));
error(iter)=sqrt(f(1)*f(1)+f(2)*f(2));
ii(iter)=iter;
if (iter > itermax)
error1 = 0.;
s=sprintf('****Did not converge within %3.0f iterations.****',itermax);
disp(s)
end
% check if error1 < 1.e-12
end
x = xx(1);
y = xx(2);
f(1) = x*normcdf((log(x/A)+(C +0.5*y^2))/y) - A * exp(-(C)*normcdf((log(x/A)+(C) +0.5*y^2))/y)-y-B;
f(2) =(x/B)*normcdf((log(x/A)+(C +0.5*y^2))/(y*1))*y-(D);
% print results
f
xx
iter
1 Comment
Oleg Komarov
on 4 Jul 2011
http://www.mathworks.com/matlabcentral/answers/6200-tutorial-how-to-ask-a-question-on-answers-and-get-a-fast-answer
Answers (1)
bym
on 4 Jul 2011
define your code as a function
function [x,y] =myNewton(A,B,C,D)
% your code here
end
Then save it as myNewton.m Then call the function in a for loop as you need it.
for k=1:length(A)
[x(k),y(k)]= myNewton(A(k),B(k),C(k),D(k));
end
Categories
Find more on Systems of Nonlinear Equations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!