创建任意大小的矩阵,其中行总和为1? [英] Creating a matrix of arbitrary size where rows sum to 1?

查看:163
本文介绍了创建任意大小的矩阵,其中行总和为1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务是为任意数量的事件创建一个模拟离散时间马尔可夫链的程序.但是,现在我正在努力的部分是创建代表概率的正确的随机矩阵.正确的随机矩阵是一个行总​​和为1的矩阵.对于给定的大小,我有点知道如何编写执行此操作的矩阵,但是问题是我不知道该怎么做为任意大小.

My task is to create a program that simulates a discrete time Markov Chain, for an arbitrary number of events. However, right now the part I'm struggling with is creating the right stochastic matrix that will represent the probabilities. A right stochastic matrix is a matrix that has row entries that sum to 1. And for a given size, I kind of know how to write the matrix that does that, however, the problem is that I don't know how to do that for an arbitrary size.

例如:这是我的3x3矩阵代码,以及我得到的输出示例.

For example: here is my code for a 3x3 matrix, along with example of the output I was getting.

http://pastebin.com/4GXpAYTM

但是,我的代码并非每次都能工作-在某些情况下,该行中的第三个条目为负数,因为前两个条目太大.而且据我所知,我不知道该如何解决.Python中没有一个函数可以使您生成随机数,这些数字具体地加起来.

However, my code doesn't work every time -- there are certain times when the third entry in the row is negative because the first two are too large. And I don't know how to get around that, as far as I know, there isn't a function in Python that makes it so that you can generate random numbers that sum to something in particular.

感谢您的帮助.

(请注意,这不是家庭作业问题,仅是为了在我的数学班上加分,教授不介意使用外部资源.)

(Note that this isn't a homework problem, it's only for extra credit in my Math class and the professor doesn't mind the use of outside sources.)

推荐答案

使用@MBo的想法:

In [16]: matrix = np.random.rand(3,3)

In [17]: matrix/matrix.sum(axis=1)[:,None]
Out[17]:
array([[ 0.25429337,  0.22502947,  0.52067716],
       [ 0.17744651,  0.42358254,  0.39897096],
       [ 0.36179247,  0.28707039,  0.35113714]])

In [18]:

这篇关于创建任意大小的矩阵,其中行总和为1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆