Solving Nonlinear Equations Repeatedly
显示 更早的评论
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 个评论
Oleg Komarov
2011-7-4
http://www.mathworks.com/matlabcentral/answers/6200-tutorial-how-to-ask-a-question-on-answers-and-get-a-fast-answer
回答(1 个)
bym
2011-7-4
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
类别
在 帮助中心 和 File Exchange 中查找有关 Systems of Nonlinear Equations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!