【问题标题】:Updating Loop of Markov Matrix: subscript out of boundaries更新马尔可夫矩阵的循环:下标超出边界
【发布时间】:2013-08-01 22:24:30
【问题描述】:

我正在尝试将矩阵相乘。矩阵中的值表示每个循环的不同概率。因此,我使用循环来更新矩阵中的值。一开始它工作得很好,但后来我得到了反馈:下标超出了界限。错误信息显示我的下一个值 [4,] 210, 323, 467。为什么它们没有显示在底部?

> initial_patient_distribtion <- c (1000,0,0)
> aaa <- c(1,0.7,0.6,0.5,0.4)
> bbb <- c(1, 0.2,0.3, 0.4, 0.5)
> ccc <- c(1, 0.1,0.1,0.1,0.1)
> 
> cycle_patient_distribution_dasa_no2nd[1,] <-initial_patient_distribtion
>  for (i in 2:length(aaa)){ 
+ trans_matrix_dasa_no2nd <- matrix (,nrow=3,ncol=3)
+ trans_matrix_dasa_no2nd[1,] <- c(aaa[i],bbb[i],ccc[i])
+ trans_matrix_dasa_no2nd[2,] <- c(0,0.5,0.5)
+ trans_matrix_dasa_no2nd[3,] <- c(0,0,1)
+ 
+ cycle_patient_distribution_dasa_no2nd[i,] <- cycle_patient_distribution_dasa_no2nd[i-1,]%*%(trans_matrix_dasa_no2nd)}
Error in `[<-`(`*tmp*`, i, , value = c(210, 323, 467)) : 
  subscript out of bounds
> 
> cycle_patient_distribution_dasa_no2nd
         [,1] [,2] [,3]
[1,] 1000    0    0
[2,]  700  200  100
[3,]  420  310  270

【问题讨论】:

  • 出于您寻求最终矩阵乘法的目的,不需要。由于您从初始状态开始,因此已经应用了转换概率。

标签: r loops matrix


【解决方案1】:

您的for 循环转到length(aaa) (5) 并在i==5 时尝试访问cycle_patient_distribution_dasa_no2nd[i,]。但是,您会看到 cycle_patient_distribution_dasa_no2nd[5,] 会引发错误,因为该矩阵的尺寸是 3x3。

如果您的代码执行您想要的操作,那么您需要将 for 循环中的结束索引更改为 3,或者修改矩阵的维度:

trans_matrix_dasa_no2nd <- matrix (,nrow=length(aaa),ncol=3)

【讨论】:

  • 谢谢,如果我更改,我会收到以下错误 Cycle_patient_distribution_dasa_no2nd[i - 1, ] %*% (trans_matrix_dasa_no2nd) 中的错误:不符合要求的参数
  • 您正在尝试将 1x3 矩阵与 5x3 矩阵相乘。内部尺寸必须相同:1x5 x 5x3 或 1x3 x 3x3。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
  • 2016-04-11
  • 1970-01-01
  • 1970-01-01
  • 2015-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多