First of all I don't want to use the reflection method, only Gram-Schmidt.
So here's the program for Gram-Schmidt:
GS[A_] := Module[{u = {}, col, e = {}, ae, t},
col = Transpose[A];(* list with the column vectors of A *)
u = Append[u, col[[1]]];
e = AppendTo[e, u[[1]]/Norm[u[[1]]]];
For[i = 2, i <= Length[A], i++, ae = 0; t = 1;
While[t <= i - 1, ae = ae - (col[[i]].e[[t]])*e[[t]]; t++];
u = AppendTo[u, col[[i]] + ae];
e = Append[e, u[[i]]/Norm[u[[i]]]]]; {u, e}]
With this simple matrix:
B = {{1, 3, 1}, {2, 2, 1}, {3, 2, 3}};
it gives
{{{1, 2, 3}, {29/14, 1/7, -(11/14)}, {14/69, -(49/69), 28/69}}, {{1/
Sqrt[14], Sqrt[2/7], 3/Sqrt[14]}, {29/Sqrt[966], Sqrt[2/
483], -(11/Sqrt[966])}, {2/Sqrt[69], -(7/Sqrt[69]), 4/Sqrt[69]}}}
Now the code for QR decomposition is:
QR[A_] := Module[{Ak, i, Q, R = {}, a = {}, col, k},
Ak = FullSimplify[GS[A]];
col = Transpose[A];(* list with the column vectors of A *)
Q = MatrixForm[Transpose[Ak[[2]]]];
For[i = 1, i <= Length[Ak[[2]]], i++, a = {}; k = 1;
While[k <= Length[col], a = AppendTo[a, col[[k]]. Ak[[2]][[i]]];
k++];
R = AppendTo[R, a]];
R = UpperTriangularize[R]; {Q, R}]
and it works for a square matrix but it doesn't work for a non square matrix, unless I change my GS code to i< Length[A]. What do I have to do for this code work in both cases?
MatrixForm
the way you do. Omit it. You can use it later, likeMatrixForm /@ QR[B]
, to make the output pretty. $\endgroup$Length[A]
inGS[]
should beLength[col]
. Then it works onB = {{1, 3, 1}, {2, 2, 1}, {3, 2, 3}, {4, 5, 6}}
. $\endgroup$