Linjär algebra

Exempel från föreläsningen

Exempel 1

Remove["Global`*"]
A1={{0.0001,1},{1,1}};
A2={{1,1},{1,1.0001}};
x={x1,x2};
b1={2,2};
b2={2,2.0001};
Print["A1 = ",MatrixForm[A1],", Det A1 = ",Det[A1],", A1x = b1: ",
Solve[A1.x==b1,x][[1]],", A1x = b2: ",Solve[A1.x==b2,x][[1]]];
Print["A2 = ",MatrixForm[A2],", Det A2 = ",Det[A2],", A2x = b1: ",
Solve[A2.x==b1,x][[1]],", A2x = b2: ",Solve[A2.x==b2,x][[1]]];

Exempel 2

Remove["Global`*"]
a={{3,1,-2},{1,-2,2},{2,1,-2}};
b={-2,1,-3};
x={x1,x2,x3};
Solve[a.x==b,x]
A={{3,1,-2,-2},{1,-2,2,1},{2,1,-2,-3}};
A2=A[[2]]-(1/3)A[[1]]
A3=A[[3]]-(2/3)A[[1]]
A3-(1/3)/(-7/3)A2

Exempel 3 (Jacobi)

Remove["Global`*"]
a={{3,-1,1},{2,-4,1},{-1,1,-4}};
u=UpperTriangularize[a,1];
d=DiagonalMatrix[Diagonal[a]];
l=a-d-u;
xold={0,0,0};
b={1,1,-1};
kmax=20;
For[k=1,k≤kmax,++k,
xnew = Inverse[d].(b-(l+u).xold);
xold=xnew;
]
Print["Jacobi: ",N[xnew]];
Print["Kontroll med NSolve: ",NSolve[a.{x1,x2,x3}==b,{x1,x2,x3}]]

Exempel 4 (Jacobi & Gauss - Seidel)

Remove["Global`*"]
a={{3,-1,1},{2,-4,1},{-1,1,-4}};
u=UpperTriangularize[a,1];
d=DiagonalMatrix[Diagonal[a]];
l=a-d-u;
b={1,1,-1};
xold={0,0,0};
kmax=20;
For[k=1,k≤kmax,++k,
xnew = Inverse[d].(b-(l+u).xold);
xold=xnew;
]
Print["Jacobi: ",N[xnew]];
xold={0,0,0};
For[k=1,k≤kmax,++k,
xnew = Inverse[l+d].(b-u.xold);
xold=xnew;
]
Print["Gauss-Seidel: ",N[xnew]];
Print["NSolve: ",NSolve[a.{x1,x2,x3}==b,{x1,x2,x3}]]

Exempel 5

Remove["Global`*"]
A={{1,2},{2,4}};
Eigensystem[A]//MatrixForm

Exempel 6 (Största egenvärde)

Remove["Global`*"]
A={{3,2,1},{2,1,-3},{1,0,1}};
xold={1.,1.,1.};
kmax=15;
For[k=1,k≤kmax,k++,
ynew=A.xold;
xnew=ynew/Norm[ynew];
lambda=xold.ynew;
xold=xnew;
]
Print["Normerad egenvektor: ",N[xnew]]
Print["Största egenvärde: ",N[lambda]]
Eigensystem[N[A]]//MatrixForm

Exempel 7 (Minsta egenvärde)

Remove["Global`*"]
A={{3,2,1},{2,1,-3},{1,0,1}};
invA=Inverse[A];
xold={1.,1.,1.};
kmax=15;
For[k=1,k≤kmax,k++,
ynew=invA.xold;
xnew=ynew/Norm[ynew];
lambda=xold.ynew;
xold=xnew;
]
Print["Normerad egenvektor: ",N[xnew]]
Print["Minsta egenvärde: ",1/N[lambda]]
Eigensystem[N[A]]//MatrixForm

Exempel 8 (Egenvärde närmast s)

Remove["Global`*"]
A={{3,2,1},{2,1,-3},{1,0,1}};
i=IdentityMatrix[3];
s=1.5;
invAsI=Inverse[A-s*i];
xold={1.,1.,1.};
kmax=15;
For[k=1,k≤kmax,k++,
ynew=invAsI.xold;
xnew=ynew/Norm[ynew];
lambda=xold.ynew;
xold=xnew;
]
Print["Normerad egenvektor: ",N[xnew]]
Print["Egenvärdet närmast ",s,": ",1/N[lambda]+s]
Eigensystem[N[A]]//MatrixForm