在R中运行以下代码时,会弹出错误消息:
“ Xt [i,]中的错误<-F * Xt [i-1,] + V: 要替换的项目数不是替换长度的倍数”
感谢您的帮助。
X=matrix(rnorm(6),100,6)
n = nrow(X)
F = diag(1,6,6); F[1,4] = F[2,5] = F[3,6] = 1
#create process & measurement noises (standard deviation)
W = diag(rnorm(1,0,0.01),6,6)
V = diag(rnorm(1,0,0.02),6,6)
#create and init Xt and Yt matrices
Xt = matrix(NA, nrow=n+1, ncol=6)
Yt = matrix(NA, nrow=n, ncol=6)
Xt[1,] = X[1,]
#test:
F * Xt[1,] + V #this is fine!!!
#before entering the loop:
for (i in 2:3)
{
Xt[i,] = F * Xt[i-1,] + V #BUT this is not!!!
Yt[i,] = Xt[i,] + W
}
答案 0 :(得分:1)
看看尺寸: 您定义
Xt[1,] = X[1,]
为您提供6x1-matrix
。下一步是计算
F * Xt[1,] + V
由于F
和V
的尺寸为6x6
,因此会产生新的6x6-matrix
。检查
dim(as.matrix(X[t,1]))
dim(F)
dim(V)
现在Xt
本身是昏暗的101x6
,因此Xt[n,]
(有点不直观)给出了转置的6x1
对象。因此,在循环中您尝试分配一个对象
F * Xt[i-1,] + V
dim(F * Xt[i-1,] + V) # this gives 6x6
到
Xt[i,]
dim(as.matrix(Xt[i,])) # this gives 6x1
因此您的尺寸不合适。我希望这能回答您的问题。
我有一个注释:
F * Xt[1,] + V
乘法F*Xt[1,]
是逐元素的乘法,而不是经典的矩阵矢量乘法。如果要对A*b
矩阵mxn
和A
-向量nx1
执行b
乘法,则必须改用%*%
。在这种情况下,V
的尺寸必须为mx1
。