Purpose
To code Gram Schmidt algorithm


INPUT MATRIX

> A <- matrix(c(1, 0, 0, 1, 1, 0), nrow = 3, ncol = 2, T)
> print(A)
     [,1] [,2]
[1,]    1    0
[2,]    0    1
[3,]    1    0

Algo

> m <- dim(A)[1]
> n <- dim(A)[2]
> Q <- matrix(data = NA, nrow = m, ncol = n)
> Q[, 1] <- A[, 1]
> Q[, 1] <- Q[, 1]/sqrt(sum(Q[, 1]^2))
> j <- 2
> for (j in 2:n) {
+     vj <- A[, j]
+     for (i in 1:(j - 1)) {
+         rij <- t(Q[, i]) * A[, j]
+         vj <- vj - rij * Q[, i]
+     }
+     rjj <- sqrt(sum(vj^2))
+     qj <- vj/rjj
+     Q[, j] <- qj
+ }

Output

> print(Q)
          [,1] [,2]
[1,] 0.7071068    0
[2,] 0.0000000    1
[3,] 0.7071068    0
> qr.Q(qr(A))
           [,1] [,2]
[1,] -0.7071068    0
[2,]  0.0000000   -1
[3,] -0.7071068    0

INPUT MATRIX

> A <- matrix(c(1, 2, 3, 0, 1, 0.5, 0, 0.1, 1), nrow = 3, ncol = 3,
+     T)
> print(A)
     [,1] [,2] [,3]
[1,]    1  2.0  3.0
[2,]    0  1.0  0.5
[3,]    0  0.1  1.0

Algo

> m <- dim(A)[1]
> n <- dim(A)[2]
> Q <- matrix(data = NA, nrow = m, ncol = n)
> Q[, 1] <- A[, 1]
> Q[, 1] <- Q[, 1]/sqrt(sum(Q[, 1]^2))
> for (j in 2:n) {
+     vj <- A[, j]
+     for (i in 1:(j - 1)) {
+         rij <- t(Q[, i]) %*% vj
+         vj <- vj - rij * Q[, i]
+     }
+     rjj <- sqrt(sum(vj^2))
+     qj <- vj/rjj
+     Q[, j] <- qj
+ }

Output

> print(Q)
     [,1]       [,2]        [,3]
[1,]    1 0.00000000  0.00000000
[2,]    0 0.99503719 -0.09950372
[3,]    0 0.09950372  0.99503719
> qr.Q(qr(A))
     [,1]        [,2]        [,3]
[1,]   -1  0.00000000  0.00000000
[2,]    0 -0.99503719 -0.09950372
[3,]    0 -0.09950372  0.99503719

The above gives Gram - Schmidt basis.. What’s wrong with this algo ?