首页 > 解决方案 > R中计算平稳分布的源代码

问题描述

看看这个链接

我试图理解以下用于查找矩阵的平稳分布的源代码:

# Stationary distribution of discrete-time Markov chain
# (uses eigenvectors)
stationary <- function(mat)
{
    x = eigen(t(mat))$vectors[,1]
    as.double(x/sum(x))
}

我自己测试了以下源代码:

> rm(list=ls())
>
> P <- matrix(c(0.66, 0.34,
+               0.66, 0.34), nrow=2, ncol=2, byrow = TRUE)
>
> x <- eigen(t(P))
> x$values
[1] 1 0

$vectors
          [,1]       [,2]
[1,] 0.8889746 -0.7071068
[2,] 0.4579566  0.7071068

> y <- x$vectors[,1]
> y
[1] 0.8889746 0.4579566
>  

看起来像命令

y <- x$vectors[,1]

正在选择矩阵的第一列。

为什么不简单地写成下面这样?

# Stationary distribution of discrete-time Markov chain
# (uses eigenvectors)
stationary <- function(mat)
{
    x = eigen(t(mat))
    y = x[,1]
    as.double(y/sum(y))
}

引入美元符号和矢量关键字的原因是什么?

标签: rmarkov-chainsmarkov

解决方案


让我们测试一下您的建议:

> P <- matrix(c(0.66, 0.34, 0.66, 0.34), nrow=2, ncol=2, byrow = TRUE)
> x <- eigen(t(P))
> print(x)
eigen() decomposition
$values
[1] 1 0

$vectors
          [,1]       [,2]
[1,] 0.8889746 -0.7071068
[2,] 0.4579566  0.7071068

> y = x[,1]

这将产生以下错误消息:

Error in x[, 1] : incorrect number of dimensions

eigen 返回一个命名列表,其中特征值命名值和特征向量命名向量。访问列表的这个组件。我们使用美元符号。因此,这就是提取矩阵的代码 x$vectors 的原因。


推荐阅读