solving non linear equations
조회 수: 3 (최근 30일)
이전 댓글 표시
clc
clear all
syms x y z xn xnp
double err
int16 n;
err=10^-4
n=2;
f1= [ x^2+x-y^2+x*y+z^2-3
5*(y^2)+y+y*z-x^2+z-7
x+y+z+y*z-z^3-3]
g=jacobian([f1],[x,y,z])
t=inv(g)
xn=sym([0.5;0.5;0.5])
xnp=-xn
i=0
while max(abs(xnp-xn))> err
xn=xnp
fc=f1
jc=t
fc(xn)=subs(fc,[x;y;z],xn)
jc(xn)=subs(jc,[x;y;z],xn)
xnp=xn-(fc*jc)
fc=[]
jc=[]
fprintf('Iteration %d: x=%.18f',i, xnp);
i=i+1
end
i am tryin here to write my own code to solve non linear system based on Newton method am pretty sure about the algorithm and how to use the mehtod in solving non linear system however am not sure about the syntax of matlab coding . can anyone please help with an explanation of these errors and how to avoid them. thanks in advance .
댓글 수: 0
답변 (2개)
VBBV
2022년 11월 18일
편집: VBBV
2022년 11월 18일
fc(:,i+1)=subs(fc,[x;y;z],xn)
jc(:,i+1)=subs(jc,[x;y;z],xn)
댓글 수: 3
VBBV
2022년 11월 18일
clc
clear all
syms x y z xn xnp
double err;
int16 n;
err=10;
n=2;
f1= [ x^2+x-y^2+x*y+z^2-3
5*(y^2)+y+y*z-x^2+z-7
x+y+z+y*z-z^3-3];
g=jacobian([f1],[x,y,z]);
t=inv(g);
xn=sym([0.5;0.5;0.5]) ;
xnp=-xn;
i=0;
while max(abs(xnp-xn)) < err % check the condition
xn=xnp;
fc=f1;
jc=t;
fc(:,i+1)=subs(fc,[x;y;z],xn);
jc(:,:,i+1)=subs(jc,[x;y;z],xn); % use the iteration index i
xnp=xn-(fc(:,i+1)'*jc(:,:,i+1)).';
fprintf('Iteration %d:\n',i+1);
fprintf(' x=%.18f\n',xnp)
i=i+1;
end
Torsten
2022년 11월 18일
편집: Torsten
2022년 11월 18일
syms x y z
errX = 10;
errF = 10;
imax = 25;
TolX = 1e-8;
TolF = 1e-8;
f = [ x^2+x-y^2+x*y+z^2-3
5*(y^2)+y+y*z-x^2+z-7
x+y+z+y*z-z^3-3];
J = jacobian(f,[x,y,z]);
Jinv = inv(J);
xi = [0.5;0.5;0.5] ;
i = 0;
while (errX > TolX || errF > TolF) && i < imax % check the condition
fi = double(subs(f,[x y z],[xi(1) xi(2) xi(3)]));
Ji = double(subs(Jinv,[x y z],[xi(1) xi(2) xi(3)]));
xip1 = xi - Ji*fi;
i = i + 1;
errX = max(abs(xip1-xi))
errF = norm(fi)
fprintf('Iteration %d:\n',i);
fprintf(' x=%.18f\n',xi)
fprintf(' f=%.18f\n',fi)
xi = xip1;
end
댓글 수: 4
Torsten
2022년 11월 26일
편집: Torsten
2022년 11월 26일
I set xi to the gams solution and your code confirmed it.
Now you can try to set the initial guess in gams to
[2.515002447346428749 ;-1.687784592789972171 ;-1.119446048550189809]
and see whether gams also confirms your MATLAB solution.
syms x y z
errX = 10;
errF = 10;
imax = 25;
TolX = 1e-8;
TolF = 1e-8;
f = [ x^2+x-y^2+x*y+z^2-3
5*(y^2)+y+y*z-x^2+z-7
x+y+z+y*z-z^3-3];
J = jacobian(f,[x,y,z]);
Jinv = inv(J);
xi = [1.253;1.166;0.278] ;
i = 0;
while (errX > TolX || errF > TolF) && i < imax % check the condition
fi = double(subs(f,[x y z],[xi(1) xi(2) xi(3)]));
Ji = double(subs(Jinv,[x y z],[xi(1) xi(2) xi(3)]));
xip1 = xi - Ji*fi;
i = i + 1;
errX = max(abs(xip1-xi))
errF = norm(fi)
fprintf('Iteration %d:\n',i);
fprintf(' x=%.18f\n',xi)
fprintf(' f=%.18f\n',fi)
xi = xip1;
end
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!