r - 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))
}
引入美元符号和矢量关键字的原因是什么?
解决方案
让我们测试一下您的建议:
> 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 的原因。
推荐阅读
- azure-data-factory - 如何使用 Azure 数据工厂计划属性?
- python - 在 PyQt5 中,如何避免改变计算机显示的缩放比例以适应屏幕显示?
- java - 如何正确实施活页夹?
- mysql - 在 MySQL 中加入逗号分隔值
- android - 无法访问隐藏,com.google.android.gms.common.internal.Hide 的类文件未找到
- typescript - 为什么一种泛型函数本身不是泛型的?
- c# - 如何在 .NET Core 2.1 WebApi 中存储数据?
- python - 无法从命令提示符直接调用python:需要输入完整安装路径
- excel - 如何自动展开下拉验证列表
- javascript - 使用表单的快速删除请求不起作用