【问题标题】:Matrix multiplication in a for loopfor循环中的矩阵乘法
【发布时间】:2020-05-09 16:12:26
【问题描述】:

以下代码在R中运行时,会弹出错误信息:

“Xt[i, ]

感谢您的帮助。

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
}

【问题讨论】:

    标签: r matrix-multiplication


    【解决方案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,] 是逐元素乘法,而不是经典的矩阵向量乘法。如果你想用 mxn-matrix Anx1-vector b 执行 A*b 乘法,你必须改用 %*%。在这种情况下,V 的维度必须为 mx1

    【讨论】:

    • 感谢 Martin -- 解决了:V/W 作为向量,%*% 作为运算符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-25
    相关资源
    最近更新 更多