我试图在 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 循环的方式有问题吗?布勒?
最佳答案
第二个循环中的范围应该是1:(j-1)
。
为了说明问题:
> 1:4-1
[1] 0 1 2 3
同时
> 1:(4-1)
[1] 1 2 3
关于r - R 中的 for 循环问题,复制 Gram-Schmidt 正交归一化算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26749477/