for循环中的矩阵乘法

时间:2020-05-09 16:12:26

标签: r matrix-multiplication

在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
}

1 个答案:

答案 0 :(得分:1)

看看尺寸: 您定义

Xt[1,] = X[1,]

为您提供6x1-matrix。下一步是计算

F * Xt[1,] + V 

由于FV的尺寸为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矩阵mxnA-向量nx1执行b乘法,则必须改用%*%。在这种情况下,V的尺寸必须为mx1