Numerical Mathematics With MATLAB
Numerical Mathematics With MATLAB
MATLAB
Reza Abazari
2008
Contents
1. Rootfinding for Nonlinear Equations ...…......………….………………….1-38
2
1. Rootfinding for Nonlinear Equations
function R = approot (f,X,epsilon)
Y=f(X);
yrange = max(Y)-min(Y);
epsilon2 = yrange*epsilon;
n=length(X);
m=0;
X(n+1)=X(n);
Y(n+1)=Y(n);
for k=2:n
if Y(k-1)*Y(k) <= 0,
m=m+1;
R(m)=(X(k-1)+X(k))/2;
end
s=(Y(k)-Y(k-1))*(Y(k+1)-Y(k));
if (abs(Y(k)) < epsilon2) & (s <= 0),
m=m+1;
R(m)=X(k);
end
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
3
yp=0.*xp; plot(xp,yp)
fprintf( 'Bisection Scheme\n\n' );
tolerance = 0.000001; it_limit = 30;
fprintf( ' It. a b c f(a) ');
fprintf( ' f(c) abs(f(c)-f(a))/2\n' );
it = 0;
Y_a = feval(f_name, a ); Y_c = feval(f_name, c );
plot([a,a],[Y_a,0]); text(a,-0.1*wid_y,'x=a')
plot([c,c],[Y_c,0]); text(c,-0.1*wid_y,'x=c')
if ( Y_a*Y_c > 0 ) fprintf( ' f(a)f(c) > 0 \n' );
else
while 1
it = it + 1;
b = (a + c)/2; Y_b = feval(f_name, b );
plot([b,b],[Y_b,0],':'); plot(b,0,'o')
if it<4, text(b, wid_y/20, [num2str(it)]), end
fprintf('%3.0f %10.6f, %10.6f', it, a, b );
fprintf('%10.6f, %10.6f, %10.6f', c, Y_a, Y_c );
fprintf( ' %12.3e\n', abs((Y_c - Y_a)/2));
if ( abs(c-a)<=tolerance )
fprintf( ' Tolerance is satisfied. \n' );break
end
if ( it>it_limit )
fprintf( 'Iteration limit exceeded.\n' ); break
end
if( Y_a*Y_b <= 0 ) c = b; Y_c = Y_b;
else a = b; Y_a = Y_b;
end
end
fprintf('Final result: Root = %12.6f \n', b );
end
x=b;
plot([x x],[0.05*wid_y 0.2*wid_y])
text( x, 0.25*wid_y, 'Final solution')
plot([x (x-wid_x*0.004)],[0.05*wid_y 0.09*wid_y])
plot([x (x+wid_x*0.004)],[0.05*wid_y 0.09*wid_y])
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
4
else
while 1
it = it + 1;
b = (a + c)/2; Y_b = feval(f_name, b );
fprintf('%3.0f %10.6f, %10.6f', it, a, b );
fprintf('%10.6f, %10.6f, %10.6f, %10.6f\n', c, Y_a, Y_b, Y_c );
if ( abs(c-a)<=tolerance )
fprintf( ' Tolerance is satisfied. \n' );break
end
if ( it>it_limit )
fprintf( 'Iteration limit exceeded.\n' ); break
end
if( Y_a*Y_b <= 0 ) c = b; Y_c = Y_b;
else a = b; Y_a = Y_b;
end
end
fprintf('Final result: Root = %12.6f \n', b );
end.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
function [c,err,yc]=bisect(f,a,b,delta)
%Input - f is the function
% - a and b are the left and right endpoints
% - delta is the tolerance
%Output - c is the zero
% - yc= f(c)
% - err is the error estimate for c
%If f is defined as an M-file function use the @ notation
% call [c,err,yc]=bisect(@f,a,b,delta).
%If f is defined as an anonymous function use the
% call [c,err,yc]=bisect(f,a,b,delta).
ya=f(a);
yb=f(b);
if ya*yb > 0,return,end
max1=1+round((log(b-a)-log(delta))/log(2));
for k=1:max1
c=(a+b)/2;
yc=f(c);
if yc==0
a=c;
b=c;
elseif yb*yc>0
b=c;
yb=yc;
else
a=c;
ya=yc;
end
if b-a < delta, break,end
end
c=(a+b)/2;
err=abs(b-a);
yc=f(c);
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
5
function [k,p,err,P] = fixpt(g,p0,tol,max1)
P(1)= p0;
for k=2:max1
P(k)=g(P(k-1));
err=abs(P(k)-P(k-1));
relerr=err/(abs(P(k))+eps);
p=P(k);
if (err<tol) | (relerr<tol),break;end
end
P=P';
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
function [S,E,G]=golden(f,a,b,delta,epsilon)
r1=(sqrt(5)-1)/2;
r2=r1^2;
h=b-a;
ya=f(a);
yb=f(b);
c=a+r2*h;
d=a+r1*h;
6
yc=f(c);
yd=f(d);
k=1;
A(k)=a; B(k)=b; C(k)=c; D(k)=d;
while (abs(yb-ya)>epsilon)|(h>delta)
k=k+1;
if (yc<yd)
b=d;
yb=yd;
d=c;
yd=yc;
h=b-a;
c=a+r2*h;
yc=f(c);
else
a=c;
ya=yc;
c=d;
yc=yd;
h=b-a;
d=a+r1*h;
yd=f(d);
end
A(k)=a; B(k)=b; C(k)=c; D(k)=d;
end
dp=abs(b-a);
dy=abs(yb-ya);
p=a;
yp=ya;
if (yb<ya)
p=b;
yp=yb;
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
function [P0,y0,err,P]=grads(F,G,P0,max1,delta,epsilon,show)
7
% Copyright by Reza Abazari 2008-04-23
% Email : [email protected]
8
ymin =F(Pmin);
if (show==1)
disp(P);
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
% The following finds the upper and lower 'y' limits for the plot based on the
% given
9
% 'x' range in the input section.
maxi = f(lxrange);
mini = f(lxrange);
for i=lxrange:(uxrange-lxrange)/10:uxrange
if f(i) > maxi
maxi = f(i);
end
if f(i) < mini
mini = f(i);
end
end
tot=maxi-mini;
mini=mini-0.1*tot;
maxi=maxi+0.1*tot;
% This graphs the function and two lines representing the two guesses
figure('Position',wind)
clf
subplot(2,1,2),fplot(f,[lxrange,uxrange])
hold on
plot([xl,xl],[maxi,mini],'y','linewidth',2)
plot([xu,xu],[maxi,mini],'g','linewidth',2)
plot([lxrange,uxrange],[0,0],'k','linewidth',1)
title('Entered function on given interval with upper and lower guesses')
% True solution
% This is how Matlab calculates the root of a non-linear equation.
xrtrue=fzero(f,xrguess);
10
n=1:nmax;
% The graphs
figure('Position',wind)
plot(n,xr,'r','linewidth',2)
title('Estimated root as a function of number of iterations')
figure('Position',wind)
subplot(2,1,1), plot(n,Et,'b','linewidth',2)
title('Absolute true error as a function of number of iterations')
subplot(2,1,2), plot(n,et,'b','linewidth',2)
title('Absolute relative true error as a function of number of iterations')
figure('Position',wind)
subplot(2,1,1), plot(n,Ea,'g','linewidth',2)
title('Absolute relative error as a function of number of iterations')
subplot(2,1,2), plot(n,ea,'g','linewidth',2)
title('Absolute relative approximate error as a function of number of
iterations')
figure('Position',wind)
bar(sigdigits,'r')
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
11
clear all
% INPUTS: Enter the following
% Function in f(x)=0
f = inline('x^3-0.165*x^2+3.993*10^(-4)');
% Upper initial guess
xu = 0.11;
% Lower initial guess
xl = 0.0;
% Lower bound of range of 'x' to be seen
lxrange = -0.02;
% Upper bound of range of 'x' to be seen
uxrange = 0.12;
%
% SOLUTION
% The following finds the upper and lower 'y' limits for the plot
% based on the given
% 'x' range in the input section.
maxi = f(lxrange);
mini = f(lxrange);
for i=lxrange:(uxrange-lxrange)/10:uxrange
if f(i) > maxi
maxi = f(i);
end
if f(i) < mini
mini = f(i);
end
end
tot=maxi-mini;
mini=mini-0.1*tot;
maxi=maxi+0.1*tot;
% This graphs the function and two lines representing the two guesses
figure('Position',wind)
clf
fplot(f,[lxrange,uxrange])
hold on
plot([xl,xl],[maxi,mini],'y','linewidth',2)
plot([xu,xu],[maxi,mini],'g','linewidth',2)
plot([lxrange,uxrange],[0,0],'k','linewidth',1)
title('Entered function on given interval with initial guesses')
hold off
%
% Iteration 1
figure('Position',wind)
xr=(xu+xl)/2;
% This graphs the function and two lines representing the two guesses
clf
subplot(3,1,2),fplot(f,[lxrange,uxrange])
hold on
plot([xl,xl],[maxi,mini],'y','linewidth',2)
plot([xu,xu],[maxi,mini],'g','linewidth',2)
12
plot([xr,xr],[maxi,mini],'r','linewidth',2)
plot([lxrange,uxrange],[0,0],'k','linewidth',1)
title('Entered function on given interval with upper and lower guesses')
% This portion adds the text and math to the top part of the figure
% window
subplot(3,1,1), text(0,1,['Iteration 1'])
text(0.2,.8,['xr = (xu + xl)/2 = ',num2str(xr)])
text(0,.6,['Finding the value of the function at the lower and upper… guesses
and the estimated root'])
text(0.2,.4,['f(xl) = ',num2str(f(xl))])
text(0.2,.2,['f(xu) = ',num2str(f(xu))])
text(0.2,0,['f(xr) = ',num2str(f(xr))])
axis off
hold off
% This portion adds the text and math to the bottom part of the
% figure window
subplot(3,1,3), text(0,1,['Check the interval between which the root… lies. Does
it lie in ( xl , xu ) or ( xr , xu )?'])
text(0,.8,[''])
text(0.2,0.6,['xu = ',num2str(xu)])
text(0.2,0.4,['xl = ',num2str(xl)])
axis off
xp=xr;
%
% Iteration 2
figure('Position',wind)
xr=(xu+xl)/2;
% This graphs the function and two lines representing the two guesses
clf
subplot(3,1,2),fplot(f,[lxrange,uxrange])
hold on
plot([xl,xl],[maxi,mini],'y','linewidth',2)
plot([xu,xu],[maxi,mini],'g','linewidth',2)
plot([xr,xr],[maxi,mini],'r','linewidth',2)
plot([lxrange,uxrange],[0,0],'k','linewidth',1)
title('Entered function on given interval with upper and lower… guesses')
% This portion adds the text and math to the top part of the figure
% window
subplot(3,1,1), text(0,1,['Iteration 2'])
text(0.2,.8,['xr = (xu + xl) / 2 = ',num2str(xr)])
text(0,.6,['Finding the value of the function at the lower and upper… guesses
and the estimated root'])
text(0.2,.4,['f(xl) = ',num2str(f(xl))])
text(0.2,.2,['f(xu) = ',num2str(f(xu))])
text(0.2,0,['f(xr) = ',num2str(f(xr))])
axis off
hold off
13
xl=xr;
else
xu=xr;
end
% This portion adds the text and math to the bottom part of the
% figure window
subplot(3,1,3), text(0,1,['Absolute relative approximate error'])
text(0,.8,['ea = abs((xr - xp) / xr)*100 = ',num2str(ea),'%'])
text(0,.4,['Check the interval between which the root lies. Does it… lie in ( xl
, xu ) or ( xr , xu )?'])
text(0.2,0.2,['xu = ',num2str(xu)])
text(0.2,0,['xl = ',num2str(xl)])
axis off
xp=xr;
%
% Iteration 3
figure('Position',wind)
xr=(xu+xl)/2;
% This graphs the function and two lines representing the two guesses
clf
subplot(3,1,2),fplot(f,[lxrange,uxrange])
hold on
plot([xl,xl],[maxi,mini],'y','linewidth',2)
plot([xu,xu],[maxi,mini],'g','linewidth',2)
plot([xr,xr],[maxi,mini],'r','linewidth',2)
plot([lxrange,uxrange],[0,0],'k','linewidth',1)
title('Entered function on given interval with upper and lower … guesses')
% This portion adds the text and math to the top part of the figure
% window
subplot(3,1,1), text(0,1,['Iteration 3'])
text(0.2,.8,['xr = (xu + xl) / 2 = ',num2str(xr)])
text(0,.6,['Finding the value of the function at the lower and upper… guesses
and the estimated root'])
text(0.2,.4,['f(xl) = ',num2str(f(xl))])
text(0.2,.2,['f(xu) = ',num2str(f(xu))])
text(0.2,0,['f(xr) = ',num2str(f(xr))])
axis off
hold off
% This portion adds the text and math to the bottom part of the
% figure window
subplot(3,1,3), text(0,1,['Absolute relative approximate error'])
text(0,.8,['ea = abs((xr - xp) / xr)*100 = ',num2str(ea),'%'])
text(0,.4,['Check the interval between which the root lies. Does it… lie in ( xl
, xu ) or ( xr , xu )?'])
14
text(0.2,0.2,['xu = ',num2str(xu)])
text(0.2,0,['xl = ',num2str(xl)])
axis off
xp=xr;
%
% Iteration 4
figure('Position',wind)
xr=(xu+xl)/2;
% This graphs the function and two lines representing the two guesses
clf
subplot(3,1,2),fplot(f,[lxrange,uxrange])
hold on
plot([xl,xl],[maxi,mini],'y','linewidth',2)
plot([xu,xu],[maxi,mini],'g','linewidth',2)
plot([xr,xr],[maxi,mini],'r','linewidth',2)
plot([lxrange,uxrange],[0,0],'k','linewidth',1)
title('Entered function on given interval with upper and lower guesses')
% This portion adds the text and math to the top part of the figure window
subplot(3,1,1), text(0,1,['Iteration 4'])
text(0.2,.8,['xr = (xu + xl) / 2 = ',num2str(xr)])
text(0,.6,['Finding the value of the function at the lower and upper guesses and
the estimated root'])
text(0.2,.4,['f(xl) = ',num2str(f(xl))])
text(0.2,.2,['f(xu) = ',num2str(f(xu))])
text(0.2,0,['f(xr) = ',num2str(f(xr))])
axis off
hold off
% This portion adds the text and math to the bottom part of the figure window
subplot(3,1,3), text(0,1,['Absolute relative approximate error'])
text(0,.8,['ea = abs((xr - xp) / xr)*100 = ',num2str(ea),'%'])
text(0,.4,['Check the interval between which the root lies. Does it lie in ( xl
, xu ) or ( xr , xu )?'])
text(0.2,0.2,['xu = ',num2str(xu)])
text(0.2,0,['xl = ',num2str(xl)])
axis off
xp=xr;
%
% Iteration 5
figure('Position',wind)
xr=(xu+xl)/2;
% This graphs the function and two lines representing the two guesses
clf
subplot(3,1,2),fplot(f,[lxrange,uxrange])
hold on
plot([xl,xl],[maxi,mini],'y','linewidth',2)
plot([xu,xu],[maxi,mini],'g','linewidth',2)
plot([xr,xr],[maxi,mini],'r','linewidth',2)
15
plot([lxrange,uxrange],[0,0],'k','linewidth',1)
title('Entered function on given interval with upper and lower guesses')
% This portion adds the text and math to the top part of the figure window
subplot(3,1,1), text(0,1,['Iteration 5'])
text(0.2,.8,['xr = (xu + xl) / 2 = ',num2str(xr)])
text(0,.6,['Finding the value of the function at the lower and upper guesses and
the estimated root'])
text(0.2,.4,['f(xl) = ',num2str(f(xl))])
text(0.2,.2,['f(xu) = ',num2str(f(xu))])
text(0.2,0,['f(xr) = ',num2str(f(xr))])
axis off
hold off
% This portion adds the text and math to the bottom part of the figure window
subplot(3,1,3), text(0,1,['Absolute relative approximate error'])
text(0,.8,['ea = abs((xr - xp) / xr)*100 = ',num2str(ea),'%'])
text(0,.4,['Check the interval between which the root lies. Does it lie in ( xl
, xu ) or ( xr , xu )?'])
text(0.2,0.2,['xu = ',num2str(xu)])
text(0.2,0,['xl = ',num2str(xl)])
axis off
xp=xr;
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
function [p,y,err]=muller(f,p0,p1,p2,delta,epsilon,max1)
16
for k=1:max1
h0=P(1)-P(3);h1=P(2)-P(3);e0=Y(1)-Y(3);e1=Y(2)-Y(3);c=Y(3);
denom=h1*h0^2-h0*h1^2;
a=(e0*h1-e1*h0)/denom;
b=(e1*h0^2-e0*h1^2)/denom;
z=-2*c/(b+disc);
p=P(3)+z;
%Sort the entries of P to find the two closest to p
if abs(p-P(2))<abs(p-P(1))
Q=[P(2) P(1) P(3)];
P=Q;
Y=f(P);
end
if abs(p-P(3))<abs(p-P(2))
R=[P(1) P(3) P(2)];
P=R;
Y=f(P);
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
function [c,err,yc]=regula(f,a,b,delta,epsilon,max1)
17
% call [c,err,yc]=regula(f,a,b,delta,epsilon,max1)
ya=f(a);
yb=f(b);
if ya*yb>0
disp('Note: f(a)*f(b) >0'),
return,
end
for k=1:max1
dx=yb*(b-a)/(yb-ya);
c=b-dx;
ac=c-a;
yc=f(c);
if yc==0,break;
elseif yb*yc>0
b=c;
yb=yc;
else
a=c;
ya=yc;
end
dx=min(abs(dx),ac);
if abs(dx)<delta,break,end
if abs(yc)<epsilon, break,end
end
c;
err=abs(b-a)/2;
yc=f(c);
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
function [p1,err,k,y]=secant(f,p0,p1,delta,epsilon,max1)
for k=1:max1
p2=p1-f(p1)*(p1-p0)/(f(p1)-f(p0));
err=abs(p2-p1);
relerr=2*err/(abs(p2)+delta);
18
p0=p1;
p1=p2;
y=f(p1);
if (err<delta)|(relerr<delta)|(abs(y)<epsilon),break,end
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
function [p0,err,k,y]=newton(f,df,p0,delta,epsilon,max1)
for k=1:max1
p1=p0-f(p0)/df(p0);
err=abs(p1-p0);
relerr=2*err/(abs(p1)+delta);
p0=p1;
y=f(p0);
if (err<delta)|(relerr<delta)|(abs(y)<epsilon),break,end
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
function [V0,y0,dV,dy]=nelder(F,V,min1,max1,epsilon,show)
%Call [V0,y0,dV,dy]=nelder(@F,V,min1,max1,epsilon,show)
19
if nargin==5,
show=0;
end
[mm n]=size(V);
[mm lo]=min(Y);
[mm hi]=max(Y);
li=hi;
ho=lo;
for j=1:n+1
if(j~=lo&j~=hi&Y(j)<=Y(li))
li=j;
end
if (j~=hi&j~=lo&Y(j)>=Y(ho))
ho=j;
end
end
cnt=0;
20
yC2=F(C2);
if (yC2<yC)
C=C2;
yC=yC2;
end
if (yC<Y(hi))
V(hi,1:n)=C;
Y(hi)=yC;
else
for j=1:n+1
if (j~=lo)
V(j,1:n)=(V(j,1:n)+V(lo,1:n))/2;
Z=V(j,1:n);
Y(j)=F(Z);
end
end
end
end
[mm lo]=min(Y);
[mm hi]=max(Y);
li=hi;
ho=lo;
for j=1:n+1
if (j~=lo&j~=hi&Y(j)<=Y(li))
li=j;
end
if (j~=hi&j~=lo&Y(j)>=Y(ho))
ho=j;
end
end
cnt=cnt+1;
P(cnt,:)=V(lo,:);
Q(cnt)=Y(lo);
end
Q=Q';
V0=V(lo,1:n);
y0=Y(lo);
dV=snorm;
dy=abs(Y(hi)-Y(lo));
if (show==1)
disp([P Q])
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
% this m-file calculates the real roots of the given polynomial using
% newton raphson technique.this m-file calls the functions in the two
% m-files named as syn_division.m and derivate.m.
% coeff_function is the 1xn matrix conatining the coeff of the
21
% polynomial.
function [final_roots,functionvalue] =
newton(coeff_function,initial_guess,error_tolerance,max_iterations)
iterations=0;
max_no_roots=size(coeff_function,2);
final_roots=0;
functionvalue=0;
for no_roots=1:max_no_roots-1
fun_root_new=initial_guess;
flag=1;
coeff_der_function=derivate(coeff_function);
order_fun=size(coeff_function,2);
order_der_fun=size(coeff_der_function,2);
while flag==1
fun_root_old=fun_root_new;
fx=0;
dfx=0;
nonzero=1;
while nonzero==1
powers=order_fun-1;
for index=1:order_fun
fx=fx+coeff_function(index)*fun_root_old^powers;
powers=powers-1;
end
powers=order_der_fun-1;
for index=1:order_der_fun
dfx=dfx+coeff_der_function(index)*fun_root_old^powers;
powers=powers-1;
end
if dfx==0
fun_root_old=fun_root_old+1;
else
nonzero=0;
end
end
iterations = iterations + 1;
fun_root_new = fun_root_old - fx/dfx;
if iterations >= max_iterations
flag=0;
elseif abs(fun_root_new-fun_root_old)<=error_tolerance
flag=0;
final_roots(no_roots)=fun_root_new;
functionvalue(no_roots)=fx;
end
end
coeff_function=syn_division(coeff_function,fun_root_new);
end
++++++++++++++++++++++++++++++++++++++++++
22
function coeff_derivative=derivate(coeff_function)
der_order=size((coeff_function),2)-1;
coeff_derivative=0;
for index=1:size((coeff_function),2)-1
coeff_derivative(index)=der_order*coeff_function(index);
der_order=der_order-1;
end
++++++++++++++++++++++++++++++++++++++++++
function coeff_second=syn_division(coeff_function,fun_root_new)
order_fun=size((coeff_function),2);
coeff_second=0;
for index=1:size((coeff_function),2)-1
if index==1
coeff_second(index)=coeff_function(index);
else
coeff_second(index)=coeff_function(index)+fun_root_new*coeff_second(index-1);
end
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
%This M.file used findzero.m and err.m that’s given the end of this m.file.
% findzero.m
for i=1:10
y=y(:); % make the points array a column array
h=(y-interval(1))*ones(1,order+1); % repeat the points column
% minus the start of the
% interval (order +1) times
23
M=[coeff_h coeff_E]; % the matrix of the LHS of the
% linear system of equations
% between every two points in the array z, we seek the point that
% maximizes the magnitude of the error function. If there is an extreme
% point (local maximum or local minimum) between such two points of the
% z array then the derivative of the error function is zero at this
% extreme point. We thus look for the extreme point by looking for the
% root of the derivative of the error function between these two
% points. If the extreme point doesn't exist then we check the value of
% the error function at the two current points of z and pick the one
% that gives maximum magnitude.
for k=1:order+2
if sign(err(z(k),fun_der,A_der,interval(1) ))~=...
sign(err(z(k+1),fun_der,A_der,interval(1)))
% check for a change in sign
y1(k)=findzero(@err,z(k),z(k+1),fun_der,A_der,interval(1));
% the extreme point that we seek
v(k)=abs(err(y1(k),fun,A1,interval(1)));
% the value of the error function at the extreme point else
% if there is no change in sign therefore there is no extreme
% point and we compare the endpoints of the sub-interval
v1=abs(err(z(k),fun,A1,interval(1)));
% magnitude of the error function at the start of the sub-interval
v2=abs(err(z(k+1),fun,A1,interval(1)));
% magnitude of the error function at the end of the sub-interval
% pick the larger of the two
if v1>v2
y1(k)=z(k);
v(k)=v1;
else
y1(k)=z(k+1);
v(k)=v2;
end
end
end
[mx ind]=max(v);
% search for the point in the extreme points array that gives maximum
% magnitude for the error function
% if the difference between this point and the corressponding point
% in the old array is less than a certain threshold then quit the loop
24
if abs(y(ind)-y1(ind)) <2^-30
break;
end
% compare it also with the following point if it is not
% the last point
if ind<length(y) & abs(y(ind+1)-y1(ind)) < 2^-30
break
end
% replace the old points with the new points
y=y1;
end
++++++++++++++++++++++++++++++++++++++++++
function y=findzero(fun,x0,x1,varargin)
% fun is the function that we need to compute its root.
% x0 and x1 are two arguments to the function such that the root that
% we seek lie between them and the function has different sign at
% these two points varargin are the other arguments of the function
% the value of the function at the first point
f0=feval(fun,x0,varargin{:});
%the value of the function at the second point
f1=feval(fun,x1,varargin{:});
% check that the sign of the function at x0 and x1 is different.
% Otherwise report an error
% Copyright by Reza Abazari 2008-04-23
% Email : [email protected]
if sign(f0)==sign(f1)
error('the function at the two endpoints must be of opposite...
signs');
end
% find a closer point to the root using the method of chords. In the
% method of chords we simply connect the two points (x0, f(x0)) and
%(x1, f(x1))using a straight line and compute the intersection point
% with this line and the horizontal axis. This new point is closer to
% the desired root
x=x0 - f0 * ((x1-x0)/(f1-f0));
% enter this root as long as the difference between the two points
% that sandwitch the desired root is larger than a certain threshold
while abs(f)>2^-52
% we keep one of the two old points that has a different sign than the
% new point and we overwrite the other old point with the new point
if sign(f)==sign(f0)
x0=x;
f0=f;
else
x1=x;
f1=f;
end
x=x0 - f0 * ((x1-x0)/(f1-f0));
f=feval(fun,x,varargin{:});
end
25
% at the end of the loop we reach the root with the desired precision and
% it is given by x
y=x;
++++++++++++++++++++++++++++++++++++++++++
% the powers out in a row and repeated for each argument to form a
% matrix for example if the order is 2 and we have 3 arguments in x
% then
% [0 1 2]
% powers= [0 1 2]
% [0 1 2]
powers=ones(length(x),1)*[0:order];
Test:
26
% plotting the error of the whole interval
x=0: 2^-15:2^-10 ;
e=err(x,fun, A1, interval(1));
plot(x,e)
xlabel('x')
ylabel('e(x)=f(x)-p(x)')
title('Error function for when approximating exp(x)')
% Example 2
fun=inline('sin(x)');
fun_der= inline('cos(x)');
interval=[0, 2^(-10)];
order =2;
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
function r = bisect(fun,xb,xtol,ftol,verbose)
27
if sign(fa)==sign(fb) % Verify sign change in the interval
error(sprintf('Root not bracketed by [%f, %f]',a,b));
end
if verbose
fprintf('\nBisection iterations for %s.m\n',fun);
fprintf(' k xm fm\n');
end
k = 0; maxit = 50; % Current and max number of iterations
while k < maxit
k = k + 1;
dx = b - a;
xm = a + 0.5*dx; % Minimize roundoff in computing the midpoint
fm = feval(fun,xm);
if verbose, fprintf('%4d %12.4e %12.4e\n',k,xm,fm); end
if (abs(fm)/fref < feps) | (abs(dx)/xref < xeps) % True when root is found
r = xm; return;
end
if sign(fm)==sign(fa)
a = xm; fa = fm; % Root lies in interval [xm,b], replace a and fa
else
b = xm; fb = fm; % Root lies in interval [a,xm], replace b and fb
end
end
warning(sprintf('root not within tolerance after %d iterations\n',k));
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
function Xb = brackPlot(fun,xmin,xmax,nx)
% --- Create data for a plot of f(x) on interval xmin <= x <= xmax
xp = linspace(xmin,xmax); yp = feval(fun,xp);
% --- Save data used to draw boxes that indicate brackets
ytop = max(yp); ybot = min(yp); % y coordinates of the box
ybox = 0.05*[ybot ytop ytop ybot ybot]; % around a bracket
c = [0.7 0.7 0.7]; % RGB color used to fill the box
28
nb = 0; Xb = []; % Xb is null unless brackets are found
for k = 1:length(f)-1
if sign(f(k))~=sign(f(k+1)) % True if sign of f(x) changes in the interval
nb = nb + 1;
Xb(nb,:) = [x(k) x(k+1)]; % Save left and right ends of the bracket
hold on; fill([x(k) x(k) x(k+1) x(k+1) x(k)],ybox,c); % Add filled box
end
end
if isempty(Xb) % Free advice
warning('No brackets found. Check [xmin,xmax] or increase nx');
return; % return without drawing a plot
end
% --- Add plot here so that curve is on top of boxes used to indicate brackets
plot(xp,yp,[xmin xmax],[0 0]);
grid on; xlabel('x');
if isa(fun,'inline')
ylabel(sprintf('Roots of f(x) = %s',formula(fun))); % label is formul in f(x)
else
ylabel(sprintf('Roots of f(x) defined in %s',fun)); % label is name of m-file
end
hold off
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
sfa = sign(feval(f,a));
Nmax = floor ( log((b-a)/TOL) / log(2.0) ) + 1
for i = 1 : Nmax
p = ( a + b ) / 2.0;
sfp = sign(feval(f,p));
if ( nargout == 0 )
disp (sprintf('\t\t %3d \t (%.10f,%.10f) \t %.10f \n', i, a, b, p))
end
if ( (b-a)<2*TOL | fp == 0 )
if ( nargout == 1 )
29
y = p;
end
return
elseif ( sfa * sfp < 0 )
b = p;
else
a = p;
sfa = sfp;
end
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
%FALSE_POS uses method of false position (regula falsi) to locate the root
% of a nonlinear function
%
% calling sequences:
% y = false_pos ( 'f', a, b, TOL, Nmax )
% false_pos ( 'f', a, b, TOL, Nmax )
%
% inputs:
% f string containing name of m-file defining function
% whose root is to be located
% a,b left and right endpoints, respectively, of interval
% known to contain root of f
% TOL absolute error convergence tolerance
% Nmax maximum number of iterations to be performed
%
% output:
% y approximate value of root
%
% NOTE:
% if FALSE_POS is called with no output arguments, the iteration
% number, the current enclosing interval and the current
% approximation to the root are displayed
%
% if the maximum number of iterations is exceeded, a message
% to this effect will be displayed and the most recent
% approximation will be returned in the output value
%
% Copyright by Reza Abazari 2008-04-23
% Email : [email protected]
old = b;
fa = feval(f,a);
fb = feval(f,b);
for i = 1 : Nmax
new = b - fb * ( b - a ) / ( fb - fa );
fnew = feval(f,new);
if ( nargout == 0 )
disp(sprintf('\t\t %3d \t (%.10f,%.10f) \t %.10f \n', i, a, b, new))
end
30
return
elseif ( fa * fnew < 0 )
b = new;
fb = fnew;
else
a = new;
fa = fnew;
end
old = new;
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
old = b; phatold = b;
fa = feval(f,a);
fb = feval(f,b);
for i = 1 : Nmax
new = b - fb * ( b - a ) / ( fb - fa );
fnew = feval(f,new);
if ( i == 1 | i == 2 )
31
if ( nargout == 0 )
disp ( sprintf ( '\t\t %3d \t %.10f \n', i, new ) )
end
else
phat = new - ( new - old ) ^ 2 / ( new - 2 * old + older );
if ( nargout == 0 )
disp ( sprintf ( '\t\t %3d \t %.10f \t %.10f \n', i, new, phat ) )
end
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
32
% to this effect will be displayed and the most recent
% approximation will be returned in the output value
%
% Copyright by Reza Abazari 2008-04-23
% Email : [email protected]
old = x0
for i = 1 : Nmax
new = feval(f,old);
if ( nargout == 0 )
disp ( sprintf ( '\t\t %3d \t %.10f \n', i, new ) )
end
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
33
% approximation will be returned in the output value
%
% Copyright by Reza Abazari 2008-04-23
% Email : [email protected]
if ( i == 1 | i == 2 )
if ( nargout == 0 )
disp ( sprintf ( '\t\t %3d \t %.10f \n', i, new ) )
end
else
phat = new - ( new - old ) ^ 2 / ( new - 2 * old + older );
if ( nargout == 0 )
disp ( sprintf ( '\t\t %3d \t %.10f \t %.10f \n', i, new, phat ) )
end
older = old;
old = new;
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
34
% TOL absolute error convergence tolerance
%
% output:
% r vector containing the roots of the polynomial
%
% NOTE:
% if POLYROOTS is called with no output arguments, the
% roots of the polynomial and the number of iterations
% required to compute each root are displayed
%
% if the maximum number of iterations is exceeded, a message
% to this effect will be displayed and the roots for which
% convergence had been achieved will be returned
%
% Copyright by Reza Abazari 2008-04-23
% Email : [email protected]
q = poly;
degree = length(poly)-1;
r = zeros ( 1, degree );
its = zeros ( 1, degree );
found = 0;
if ( done == 0 )
disp('Maximum number of iterations exceeded')
return
end;
if ( abs(imag(new)) == TOL )
found = found + 1;
r(found) = real(new);
its(found) = done;
q = deconv ( q, [ 1 -real(new) ] );
else
r(found+1) = new;
r(found+2) = conj(new);
its(found+1) = done;
its(found+2) = done;
found = found + 2;
q = deconv ( q, conv ( [1 -new], [1 -conj(new)] ) );
end;
q = real(q);
end;
if ( found == degree - 2 )
if ( q(2) == 0 )
r(degree-1) = sqrt ( -q(3)/q(1) );
r(degree) = -r(degree-1);
else
r(degree-1)=2*q(3)/(-q(2)-sign(q(2))*sqrt(q(2)*q(2)-4*q(1)*q(3)));
r(degree) = q(3) / ( r(degree-1) * q(1) );
end;
else
r(degree) = -q(2)/q(1);
end;
if ( nargout == 0 )
35
disp ( [r' its'] )
end;
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
N=length(P);
for k=1:max1
X=P;
err=abs(norm(X-P));
relerr=err/(norm(X)+eps);
P=X;
iter=k;
if (err<delta)|(relerr<delta)
break
end
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
function [P,iter,err]=newdim(F,JF,P,delta,epsilon,max1)
36
Y=F(P);
for k=1:max1
J=JF(P);
Q=P-(J\Y')';
Z=F(Q);
err=norm(Q-P);
relerr=err/(norm(Q)+eps);
P=Q;
Y=Z;
iter=k;
if (err<delta)|(relerr<delta)|(abs(Y)<epsilon)
break
end
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
done = 0;
n = length ( f ) - 1;
fp = polyder ( f );
fp2 = polyder ( fp );
for i = 1 : Nmax
fx = polyval ( f, x0 );
fpx = polyval ( fp, x0 );
fp2x = polyval ( fp2, x0 );
gx = fpx / fx;
g2 = gx * gx;
hx = g2 - fp2x / fx;
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
37
function y = steffensen ( f, x0, TOL, Nmax )
phat = p2 - ( p2 - p1 ) ^ 2 / ( p2 - 2 * p1 + p0 );
if ( nargout == 0 )
disp ( sprintf ( '\t\t %3d \t %.10f \n', i, phat ) )
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
38
39
2. Numerical Linear Algebra
function [P,iter]= seidel(G,P,delta, max1)
N=length(P);
for k=1:max1
X=P;
err=abs(norm(X-P));
relerr=err/(norm(X)+eps);
P=X;
iter=k;
if (err<delta)|(relerr<delta)
break
end
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
function [p,Q]=steff(f,df,p0,delta,epsilon,max1)
40
R=zeros(max1,3);
R(1,1)=p0;
for k=1:max1
for j=2:3
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
function [P,iter,err]=newdim(F,JF,P,delta,epsilon,max1)
41
% Copyright by Reza Abazari 2008-04-23
% Email : [email protected]
Y=F(P);
for k=1:max1
J=JF(P);
Q=P-(J\Y')';
Z=F(Q);
err=norm(Q-P);
relerr=err/(norm(Q)+eps);
P=Q;
Y=Z;
iter=k;
if (err<delta)|(relerr<delta)|(abs(Y)<epsilon)
break
end
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
function x = gauss_elim ( A, b )
% Gaussian elimination
42
for i = 1 : nrow - 1
if ( A(i,i) == 0 )
t = min ( find ( A(i+1:nrow,i) ~= 0 ) + i );
if ( isempty(t) )
disp ( 'gauss_elim error: A matrix is singular' );
return
end;
temp = A(i,:); tb = b(i);
A(i,:) = A(t,:); b(i) = b(t);
A(t,:) = temp; b(t) = tb;
end;
for j = i+1 : nrow
m = -A(j,i) / A(i,i);
A(j,i) = 0;
A(j, i+1:nrow) = A(j, i+1:nrow) + m * A(i, i+1:nrow);
b(j) = b(j) + m * b(i);
end;
end;
%
% back substitution
%
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
43
% Copyright by Reza Abazari 2008-04-23
% Email : [email protected]
n = length ( b );
[r c] = size ( A );
if ( c ~= n )
disp ( 'gauss_seidel error: matrix dimensions and vector dimension not
compatible' )
return
end;
xnew = zeros ( 1, n );
if ( nargout == 0 )
s = sprintf ( '%3d \t %10f ', 0, xold(1) );
for j = 2 : n
s = sprintf ( '%s%10f ', s, xold(j) );
end;
disp ( s );
end;
if ( nargout == 0 )
s = sprintf ( '%3d \t %10f ', its, xnew(1) );
for j = 2 : n
s = sprintf ( '%s%10f ', s, xnew(j) );
end;
disp ( s );
end;
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
44
% F vector-valued function of a vector argument which
% defines the system of equations to be solved
% J matrix-valued function which computes the Jacobian
% associated with the function F
% x0 vector containing initial guess for solution of
% nonlinear system
% TOL convergence tolerance - applied to maximum norm of
% difference between successive approximations
% NMax maximum number of iterations to be performed
%
% output:
% y approximate solution of nonlinear system
%
%
% NOTE:
% if BROYDEN is called with no output arguments, each
% approximation to the solution is displayed
%
% if the maximum number of iterations is exceeded, a meesage
% to this effect will be displayed and the current approximation
% will be returned in the output value
%
% Copyright by Reza Abazari 2008-04-23
% Email : [email protected]
Fold = feval(F,x0)';
Jold = feval(J,x0);
A0 = inv ( Jold );
dx = -A0 * Fold;
x0 = x0 + dx;
if ( nargout == 0 )
disp ( x0' )
end
for i = 2 : Nmax
Fnew = feval(F,x0)';
dy = Fnew - Fold;
u = A0 * dy;
v = dx' * A0;
denom = dx' * u;
A0 = A0 + ( dx - u ) * v / denom;
dx = -A0 * Fnew;
x0 = x0 + dx;
if ( nargout == 0 )
disp ( x0' )
end
end
45
if ( nargout == 1 )
y = x0;
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
n = length ( b );
[r c] = size ( A );
if ( c ~= n )
disp('conj_grad error: matrix dimensions and vector dimension not compatible')
return
end;
if ( nargout == 0 )
s = sprintf ( '%3d \t %10f ', 0, x(1) );
for j = 2 : n
s = sprintf ( '%s%10f ', s, x(j) );
end;
disp ( s );
end;
r = A * x - b;
delta0 = r' * r;
d = -r;
46
h = A * d;
lambda = delta0 / ( d' * h );
x = x + lambda * d;
r = r + lambda * h;
delta1 = r' * r;
if ( nargout == 0 )
s = sprintf ( '%3d \t %10f ', its, x(1) );
for j = 2 : n
s = sprintf ( '%s%10f ', s, x(j) );
end;
disp ( s );
end;
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
n = length ( b );
47
[r c] = size ( A );
if ( c ~= n )
disp('jacobi error: matrix dimensions and vector dimension not compatible')
return
end;
xnew = zeros ( 1, n );
if ( nargout == 0 )
s = sprintf ( '%3d \t %10f ', 0, xold(1) );
for j = 2 : n
s = sprintf ( '%s%10f ', s, xold(j) );
end;
disp ( s );
end;
if ( nargout == 0 )
s = sprintf ( '%3d \t %10f ', its, xnew(1) );
for j = 2 : n
s = sprintf ( '%s%10f ', s, xnew(j) );
end;
disp ( s );
end;
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
48
% triangular portion of the matrix lu
% pvt vector which indicates the permutation of the rows
% performed during the decomposition process
% NOTE:
% this routine performs partial pivoting during the
% decomposition process
%
% the system Ax = b can be solved by first applying LUfactor
% to the coefficient matrix A and then applying the companion
% routine, LUsolve, for each right-hand side vector b
%
% Copyright by Reza Abazari 2008-04-23
% Email : [email protected]
%
% initialize row pointers
%
for i=1:nrow
pvt(i) = i;
end
for i = 1 : nrow - 1
%
% partial pivoting
%
t =min(find(abs(A(pvt(i:nrow),i)) == max(abs(A(pvt(i:nrow),i))))+ i-1 );
if ( t ~= i )
temp = pvt(i);
pvt(i) = pvt(t);
pvt(t) = temp;
end
%
% terminate if matrix is singular
%
if ( A(pvt(i),i) == 0 )
disp ( 'LUfactor error: coefficient matrix is singular' );
lu = A;
return
end
%
% elimination steps
%
for j = i+1 : nrow
m = -A(pvt(j),i) / A(pvt(i),i);
A(pvt(j),i) = -m;
A(pvt(j), i+1:nrow) = A(pvt(j), i+1:nrow) + m * A(pvt(i), i+1:nrow);
end
end
lu = A;
49
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
%
% forward substitution
%
z(1) = b(pvt(1));
for i = 2 : nrow
z(i) = b(pvt(i)) - sum ( z(1:i-1) .* lu(pvt(i), 1:i-1) );
end
%
% back substitution
%
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
50
%NEWTON_SYS solve the system of nonlinear equations F(x) = 0 using
% Newton's method
%
% calling sequences:
% y = newton_sys ( F, J, x0, TOL, Nmax )
% newton_sys ( F, J, x0, TOL, Nmax )
%
% inputs:
% F vector-valued function of a vector argument which
% defines the system of equations to be solved
% J matrix-valued function which computes the Jacobian
% associated with the function F
% x0 vector containing initial guess for solution of
% nonlinear system
% TOL convergence tolerance - applied to maximum norm of
% difference between successive approximations
% NMax maximum number of iterations to be performed
%
% output:
% y approximate solution of nonlinear system
%
% dependencies:
% this routine uses both LUfactor and LUsolve
%
% NOTE:
% if NEWTON_SYS is called with no output arguments, each
% approximation to the solution is displayed
%
% if the maximum number of iterations is exceeded, a meesage
% to this effect will be displayed and the current approximation
% will be returned in the output value
%
% Copyright by Reza Abazari 2008-04-23
% Email : [email protected]
old = x0;
for i = 1 : Nmax
Fold = feval(F,old);
Jold = feval(J,old);
[lu pvt] = LUfactor ( Jold );
dx = LUsolve ( lu, -Fold, pvt );
new = old + dx;
if ( nargout == 0 )
disp ( new )
end
51
y = new;
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
function y = tridiagonal ( c, a, b, r )
n = length ( a );
%
% factorization step
%
for i = 1 : n-1
b(i) = b(i) / a(i);
a(i+1) = a(i+1) - c(i) * b(i);
end
%
% forward substitution
%
52
%
% back substitution
%
for i = n-1 : -1 : 1
r(i) = r(i) - r(i+1) * b(i);
end
if ( nargout == 0 )
disp ( r )
else
y = r;
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
n = length ( b );
[r c] = size ( A );
if ( c ~= n )
disp ( 'sor error: matrix dimensions and vector dimension not compatible' )
return
end
xnew = zeros ( 1, n );
if ( nargout == 0 )
53
s = sprintf ( '%3d \t %10f ', 0, xold(1) );
for j = 2 : n
s = sprintf ( '%s%10f ', s, xold(j) );
end
disp ( s );
end
if ( nargout == 0 )
s = sprintf ( '%3d \t %10f ', its, xnew(1) );
for j = 2 : n
s = sprintf ( '%s%10f ', s, xnew(j) );
end
disp ( s );
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
54
% Nmax maximum number of iterations to be performed
%
% outputs:
% lambda approximation to dominant eigenvalue of A
% v an eigenvector of A corresponding to the eigenvalue
% lambda - vector will be normalized to unit length
% in the Euclidean norm
%
% NOTE:
% if SYMPOWER is called with no output arguments, the
% iteration number, the current eigenvector approximation,
% the current eigenvalue approximation and an estimate of
% the rate of convergence of the eigenvalue sequence will
% be displayed
%
% if the maximum number of iterations is exceeded, a message
% to this effect will be displayed and the most recent
% approximations to the dominant eigenvalue and its corresponding
% eigenvector will be returned in the output values
%
% Copyright by Reza Abazari 2008-04-23
% Email : [email protected]
[r c] = size ( A );
[rx rc] = size ( x );
if ( rx == 1 ) x = x'; rx = rc; end;
if ( r ~= c )
disp ( 'sympower error: matrix must be square' );
return;
elseif ( r ~= rx )
disp ( 'sympower error: dimensions of matrix and vector are not compatible' );
return;
end
x = x / sqrt ( sum ( x .* x ) );
mu_old = 0;
if ( nargout == 0 )
s = sprintf ( '%3d \t %10f ', 0, x(1) );
for j = 2 : rx
s = sprintf ( '%s%10f ', s, x(j) );
end
disp ( s );
end
for i = 1 : Nmax
xnew = A * x;
mu = sum ( x .* xnew );
xnew = xnew / sqrt ( sum ( xnew .* xnew ) );
if ( nargout == 0 )
s = sprintf ( '%3d \t %10f ', i, xnew(1) );
for j = 2 : rx
s = sprintf ( '%s%10f ', s, xnew(j) );
end
s = sprintf ( '%s \t %10f', s, mu );
if ( i >= 3 )
s = sprintf ( '%s \t \t %10f', s, abs((mu-mu_old)/(mu_old-mu_older)) );
55
end
disp ( s );
end
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
56
% 'lambda'
%
% dependencies:
% this routine makes use of the routine SYMPOWER
%
% NOTE:
% if the maximum number of iterations is exceeded during any
% call to SYMPOWER, a message to this effect will be displayed
%
% Copyright by Reza Abazari 2008-04-23
% Email : [email protected]
[r c] = size ( A );
if ( r ~= c )
disp ( 'hotelling error: matrix must be square' );
return;
end
n = r;
l = zeros ( 1, num_pairs );
v = zeros ( n, num_pairs );
lambda = l;
vects = v;
return;
%++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function B = hd ( A, l, v )
B = A - ( l / dot ( v, v ) ) * v * v';
return;
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
57
% Nmax maximum number of iterations to be performed
%
% outputs:
% lambda approximation to dominant eigenvalue of A
% v an eigenvector of A corresponding to the eigenvalue
% lambda - vector will be normalized to unit length
% in the maximum norm
%
% dependencies:
% this routine makes use of both LUfactor and LUsolve from
% "Systems of Equations" library
%
% NOTE:
% if INV_POWER is called with no output arguments, the
% iteration number, the current eigenvector approximation,
% the current eigenvalue approximation and an estimate of
% the rate of convergence of the eigenvalue sequence will
% be displayed
%
% if the maximum number of iterations is exceeded, a message
% to this effect will be displayed and the most recent
% approximations to the eigenvalue nearest to q and its
% corresponding eigenvector will be returned in the output values
%
% Copyright by Reza Abazari 2008-04-23
% Email : [email protected]
[r c] = size ( A );
[rx rc] = size ( x );
if ( rc == 1 ) x = x'; rc = rx; end;
if ( r ~= c )
disp ( 'inv_power error: matrix must be square' );
return;
elseif ( r ~= rc )
disp ( 'inv_power error: dimensions of matrix and vector are not compatible' );
return;
end;
if ( nargout == 0 )
s = sprintf ( '%3d \t %10f ', 0, x(1) );
for j = 2 : rc
s = sprintf ( '%s%10f ', s, x(j) );
end;
disp ( s );
end;
for i = 1 : Nmax
xnew = LUsolve ( lu, x, pvt );
mu = xnew(p);
p = min ( find ( abs(xnew) == max(abs(xnew)) ) );
xnew = xnew / xnew(p);
58
if ( nargout == 0 )
s = sprintf ( '%3d \t %10f ', i, xnew(1) );
for j = 2 : rc
s = sprintf ( '%s%10f ', s, xnew(j) );
end
s = sprintf ( '%s \t %10f', s, 1/mu+q );
if ( i >= 2 )
s = sprintf ( '%s \t \t %10f', s, abs((mu-mu_old)/(mu_old-mu_older)) );
end
disp ( s );
end
end
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
59
% in the eigenvector seqeunce)
% Nmax maximum number of iterations to be performed during
% each call to either POWER_METHOD or INV_POWER
%
% outputs:
% lambda vector containing the largest/smallest 'num_pairs'
% eigenvalues of the matrix A
% vects matrix containing eigenvectors corresponding to the
% entries in the output vector 'lambda'
% - the i-th column of this matrix is an eigenvector,
% normalized to unit length in the maximum norm,
% corresponding to the i-th entry in the vector
% 'lambda'
%
% dependencies:
% this routine makes use of the routines POWER_METHOD and
% INV_POWER
%
% NOTE:
% if the maximum number of iterations is exceeded during any
% call to either POWER_METHOD or INV_POWER, a message to this
% effect will be displayed
%
% Copyright by Reza Abazari 2008-04-23
% Email : [email protected]
[r c] = size ( A );
if ( r ~= c )
disp ( 'wielandt error: matrix must be square' );
return;
end;
n = r;
if ( num_pairs < 0 )
num_pairs = abs(num_pairs);
small = 1;
else
small = 0;
end;
l = zeros ( 1, num_pairs );
v = zeros ( n, num_pairs );
j = zeros ( 1, num_pairs );
x = zeros ( num_pairs, n );
if ( small == 0 )
[l(1) v(:,1)] = power_method ( A, rand(n,1), TOL, Nmax );
else
[l(1) v(:,1)] = inv_power ( A, 0, rand(1,n), TOL, Nmax );
end;
for i = 2:num_pairs
j(i) = min ( find ( abs(v(:,i-1)) == max(abs(v(:,i-1))) ) );
x(i,1:n+2-i) = A(j(i),:);
A = wd ( A, n+2-i, j(i), v(:,i-1) );
if ( small == 0 )
[l(i) v(1:n-i+1,i)] = power_method ( A, rand(n-i+1,1), TOL, Nmax );
else
[l(i) v(1:n-i+1,i)] = inv_power ( A, 0, rand(1,n-i+1), TOL, Nmax );
end;
60
end;
for i=num_pairs:-1:2
for k=i:-1:2
temp = [v(1:j(k)-1, i); 0; v(j(k):n-k+1, i)];
v(1:n-k+2,i) = (l(i) - l(k-1))*temp +(x(k,1:n+2-k)*temp)*v(1:n-k+2,k-
1)/v(j(k),k-1);
end;
p = min ( find ( abs(v(:,i)) == max(abs(v(:,i))) ) );
v(:,i) = v(:,i) / v(p,i);
end;
lambda = l;
vects = v;
return;
%++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function B = wd ( A, n, j, v )
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
61
% if the maximum number of iterations is exceeded, a message
% to this effect will be displayed and the most recent
% approximations to the dominant eigenvalue and its corresponding
% eigenvector will be returned in the output values
%
% Copyright by Reza Abazari 2008-04-23
% Email : [email protected]
[r c] = size ( A );
[rx rc] = size ( x );
if ( rx == 1 ) x = x'; rx = rc; end;
if ( r ~= c )
disp ( 'power_method error: matrix must be square' );
return;
elseif ( r ~= rx )
disp ( 'power_method error: dimensions of matrix and vector are not compatible'
);
return;
end;
if ( nargout == 0 )
s = sprintf ( '%3d \t %10f ', 0, x(1) );
for j = 2 : rx
s = sprintf ( '%s%10f ', s, x(j) );
end;
disp ( s );
end;
for i = 1 : Nmax
xnew = A * x;
mu = xnew(p);
p = min ( find ( abs(xnew) == max(abs(xnew)) ) );
xnew = xnew / xnew(p);
if ( nargout == 0 )
s = sprintf ( '%3d \t %10f ', i, xnew(1) );
for j = 2 : rx
s = sprintf ( '%s%10f ', s, xnew(j) );
end;
s = sprintf ( '%s \t %10f', s, mu );
if ( i >= 2 )
s = sprintf ( '%s \t \t %10f', s, abs((mu-mu_old)/(mu_old-mu_older)) );
end;
disp ( s );
end;
62
end;
end;
disp ( 'power_method error: Maximum number of iteration exceeded' );
if ( nargout >= 1 ) lambda = mu; end;
if ( nargout >= 2 ) v = xnew;
end.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
63
% Email : [email protected]
n = length(a);
if ( length(b) == n-1 ) b(2:n) = b(1:n-1); end;
c = zeros ( 1, n );
s = zeros ( 1, n );
shift = 0;
togo = n;
if ( nargout >= 2 )
if ( nargin >= 5 )
v = vects;
else
v = eye(n);
end;
end;
if ( togo == 1 )
lambda(1) = a(1) + shift;
disp ( its );
return;
end;
shift = shift + s;
for i = 1:togo
a(i) = a(i) - s;
end;
oldb = b(2);
for i = 2:togo
j = i-1;
r = sqrt ( a(j)^2 + oldb^2 );
c(i) = a(j) / r;
s(i) = oldb / r;
a(j) = r;
temp1 = c(i)*b(i) + s(i)*a(i);
temp2 = -s(i)*b(i) + c(i)*a(i);
b(i) = temp1;
a(i) = temp2;
if ( i ~= togo ) oldb = b(i+1); b(i+1) = c(i)*b(i+1); end;
end;
64
b(i+1) = s(i+1)*a(i+1);
end;
a(togo) = c(togo)*a(togo);
if ( nargout >= 2 )
for i = 2 : togo
col1 = v(:,i-1) * c(i) + v(:,i) * s(i);
v(:,i) = -s(i) * v(:,i-1) + c(i) * v(:,i);
v(:,i-1) = col1;
end;
end;
end;
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
65
for i = 1 : n-2
w = zeros ( n, 1 );
x = A(:,n-i+1);
alpha = - sign(x(n-i)) * norm ( x(1:n-i) );
if ( alpha ~= 0 )
w(n-i) = sqrt ( (1/2) * ( 1 - x(n-i)/alpha ) );
w(1:n-i-1) = -(1/2) * x(1:n-i-1) / ( alpha * w(n-i) );
u = A * w;
K = dot ( w, u );
q = u - K * w;
A = A - 2*w*q' - 2*q*w';
a = diag(A);
b = zeros ( n, 1 );
for i = 2:n b(i) = A(i,i-1);
end;
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
3. Polynomial Interpolation
66