我有一些R代码尝试在方阵A上完成LU分解。但是当我尝试运行代码时,我得到一个错误说;
Error in U[j, i] : subscript out of bounds
似乎变量j的for循环没有停止,起初我认为这是因为i变量循环到nrow(A) - 1,然后在结束循环之前加1,类似于C但是,我打印出i,j和k变量,似乎j变量没有停止。任何想法都是为什么?
LUD <- function(A) {
if (!is.matrix(A)) {
warning("argument is not a matrix: returning NA")
return(NA)
}
L <- matrix(nrow = nrow(A), ncol = ncol(A))
P <- matrix(nrow = nrow(A), ncol = ncol(A))
for (i in 1:nrow(A)) {
for (j in 1:nrow(A)) {
if (i == j) {
L[i, j] = 1
P[i, j] = 1
} else {
L[i, j] = 0
P[i, j] = 0
}
}
}
U = A
for (i in 1:(nrow(A) - 1)) {
max = which(U == max(U[i:nrow(A), i]), arr.ind = TRUE)
k[i] = max[, 1] ##finding position of largest element
temp = U
U[i, ] = temp[k[i], ] ## pivoting rows in U
U[k[i], ] = temp[i, ]
temp = L
L[i, ] = temp[k[i], ] ## pivoting rows in L
L[k[i], ] = temp[i, ]
temp = P
P[i, ] = temp[k[i], ] ##pivoting rows in P
P[k[i], ] = temp[i, ]
print(i)
for (j in i + 1:nrow(A)) {
print(j + 10)
L[j, i] = U[j, i]/U[i, i]
for (k in i:nrow(A))
{
U[j, k] = U[j, k] - L[j, i] * U[i, k]
print(k + 100)
}
}
}
}
编辑:这是我的矩阵:
A<-matrix(1:16,nrow=4,ncol=4)
答案 0 :(得分:2)
我的猜测是你需要查看循环的序列。尝试
改变第二个循环
for(j in i + 1:nrow(A))
至
for(j in (i + 1):nrow(A))