Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save CasperBHansen/4476553 to your computer and use it in GitHub Desktop.
Save CasperBHansen/4476553 to your computer and use it in GitHub Desktop.
Diagonalize[A_, exp_] :=
(
(* Variables used *)
n = (Dimensions[A])[[1]];
Id = IdentityMatrix[n];
d = Det[A];
(* Print basic information *)
Print["A = ", (A // MatrixForm)];
Print["k (Exponent) = ", exp];
Print["Det(A) = ", d];
Print["P(\[Lambda]) = ", (P = CharacteristicPolynomial[A, x])];
(* Solve for \[Lambda]'s *)
Print["Solutions for P(x)=0 (Eigenvalues):"];
tmp = Solve[P == 0, x];
\[Lambda] = {};
For[i = 1, i < (n + 1),
i++, (val = tmp[[i]][[1]][[2]];
If[MemberQ[\[Lambda], val], , AppendTo[\[Lambda], val]])];
(* Print \[Lambda]'s *)
For[i = 1, i < (Length[\[Lambda]] + 1), i++,
Print[Subscript["\[Lambda]", i], " = ", Part[\[Lambda], i]]];
(* Solve for v's *)
Print["Solutions for (A - \[Lambda]I)v=0 (Eigenvectors):"];
v = {};
For[i = 1, i < (Length[\[Lambda]] + 1), i++,
(
tmp = NullSpace[A - Id*Part[\[Lambda], i]];
(* Split potential multi-column matrices *)
For[j = 1, j < (Dimensions[Transpose[tmp]][[2]] + 1), j++,
AppendTo[v, tmp[[j]]]];
)];
(* Print v's *)
For[i = 1, i < (Length[v] + 1), i++,
Print[Subscript["v", i], " = ", Part[v, i] // MatrixForm]];
(* Calculate diagonalization *)
Si = Transpose[v];
S = Inverse[Si];
Dia = MatrixPower[S.A.Si, exp];
(* Print Results *)
Print[Superscript["S", -1], " = ", Si // MatrixForm];
Print["S = ", S // MatrixForm];
If[exp == 1,
(
Print["D = SA", Superscript["S", -1], " = ", Dia // MatrixForm];
Print["A = ", Superscript["S", -1], "DS = ",
Si.Dia.S // MatrixForm];
),
(
Print[Superscript["D", exp], " = S", Superscript["A", exp],
Superscript["S", -1], " = ", Dia // MatrixForm];
Print[Superscript["A", exp], " = ", Superscript["S", -1],
Superscript["D", exp], "S = ", Si.Dia.S // MatrixForm];
)];
Return[Dia];
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment