R中的for循环出现问题,复制了Gram-Schmidt Orthonormalization算法

时间:2014-11-05 03:59:41

标签: r algorithm

我正在尝试为R中的线性代数类复制Gram-Schmidt正交归一化算法。首先,我生成一些数据,并将其存储在矩阵A

a1<-c(1,2,3,4,5,6)
a2<-c(4,5,2,9,1,2)
a3<-c(2,2,2,3,3,3)
A<-cbind(a1,a2,a3)

然后我运行gram-schmidt正交归一化算法将A的列转换为正交集,存储在矩阵Q中。

R=matrix(0,nrow=ncol(A),ncol=ncol(A))
Q=A
R[1,1]=sqrt(sum(Q[,1]*Q[,1])) #calculate nrom of q1, store in R
Q[,1]=(1/R[1,1])*Q[,1] #transform q1 into a unit vector, using the norm stored in R.
for(j in 2:ncol(Q))
{
    for(i in 1:j-1)
    {
        R[i,j]=sum(Q[,i]*Q[,j]) 
        Q[,j]=Q[,j] - R[i,j]*Q[,i] 
    }
    R[j,j]=sqrt(sum(Q[,j]*Q[,j]))#calulate the norm of qj, store in the main diagonal of R
    Q[,j]=(1/R[j,j])*Q[,j] #transform qj into a unit vector, using the norm stored in R.
}

我的算法看起来与R:Gram Schmidt with R

这里编码的算法非常相似

但是,每次运行算法时都会生成此错误:

Error in Q[, j] = Q[, j] - R[i, j] * Q[, i] : replacement has length zero

我无法弄清楚这里有什么问题。如果我逐行运行代码,并设置i = 1,j = 2,它运行该行的第一次计算就好了。我如何指定或嵌套我的for循环有什么问题吗? Bueller?

1 个答案:

答案 0 :(得分:3)

第二个循环中的范围应为1:(j-1)

说明问题:

> 1:4-1
[1] 0 1 2 3

,而

> 1:(4-1)
[1] 1 2 3