Manual Cholesky calculation solutions in R

时间:2015-05-04 19:26:29

标签: r loops matrix

My ultimate goal is to use a cholesky decomposition matrix for a large dataset with certain rows zeroed out. Since you cannot solve a system of equations that is not positive definite I have coded R to manually solve against the Cholesky matrix. Before applying to my full data I am using a small matrix to debug my code.

I am trying to solve the following system of equations:

L = matrix(c(1, 2, 4, 7,
             0, 3, 5, 8,
             0, 0, 6, 9,
             0, 0, 0, 10), nrow=4)
R = c(1, 8, 32, 90)

Using these matrices, my X matrix would solve to be c(1,2,3,4) I have code that solves this set of equations perfectly.

FYI: if LX = R, Xi = (Ri - sum(Lij * Xi)) / Lii

Now, if I were to zero out the third column of the L matrix everything goes haywire. R tells me that the x[1, 1]:x[j, 1] result would be too long of a vector. I am trying to tell R to just skip that row and automatically insert a 0, which seems to be working. But then the following row does not come out correctly, giving the warning message "In (L[i, 1]:L[i, j]) * (x[1, ]:x[j, ]) : longer object length is not a multiple of shorter object length"

I am getting the solution c(1, 2, 0, 7.4); which should be c(1, 2, 0, 6.7)

Here is my code:

chol_loop<-function(R, L){
    n = dim(L)[1]
    x = matrix(0,n,1)
    for(i in 1:n){
        if(i == 1){
        x[i, 1] = R[i, 1] / L[i, i]
            }
        else{
            for(j in 1:(i - 1)){
        sum = 0
        sum <- sum((L[i, 1]:L[i, j]) * (x[1, ]:x[j, ]));
            }
            if((L[i, i]) == 0){
                x[i, 1] = 0
            }
        else{
     x[i, 1] = (R[i, 1] - sum) / L[i, i];
    }
    }
 }
    return(x);
 }

X <- chol_loop(R, L)
X

Thanks in advance for your help!

0 个答案:

没有答案