Gram Schmidt with R

后端 未结 4 1773
青春惊慌失措
青春惊慌失措 2020-12-31 21:30

Here is a MATLAB code for performing Gram Schmidt in page 1 http://web.mit.edu/18.06/www/Essays/gramschmidtmat.pdf

I am trying for hours and hours to perform this wi

4条回答
  •  一个人的身影
    2020-12-31 22:01

    Here a version very similar to yours but without the use of the extra variabale v. I use directly the Q matrix. So no need to use drop. Of course since you have j-1 in the index you need to add the condition j>1.

    f=function(x){
      m <- nrow(x)
      n <- ncol(x)
      Q <- matrix(0, m, n)
      R <- matrix(0, n, n)
      for (j in 1:n) {
        Q[, j] <- x[, j]
        if (j > 1) {
          for (i in 1:(j - 1)) {
            R[i, j] <- t(Q[, i]) %*% Q[, j]
            Q[, j] <- Q[, j] - R[i, j] * Q[, i]
          }
        }
        R[j, j] <- max(svd(Q[, j])$d)
        Q[, j] <- Q[, j]/R[j, j]
      }
      return(list(Q = Q, R = R))
    }
    

    EDIT add some benchmarking:

    To get some real case I use the Hilbert matrix from the Matrix package.

    library(microbenchmark)
    library(Matrix)
    A <- as.matrix(Hilbert(100))
    microbenchmark(grahm_schimdtR(A),
                   grahm_schimdtCpp(A),times = 100L)
    
    Unit: milliseconds
    expr       min         lq     median        uq        max neval
    grahm_schimdtR(A) 330.77424 335.648063 337.443273 343.72888 601.793201   100
    grahm_schimdtCpp(A)   1.45445   1.510768   1.615255   1.66816   2.062018   100
    

    As expected CPP solution is really fster.

提交回复
热议问题