简体   繁体   English

如何在python中使用for循环创建NXN矩阵

[英]How to create a NXN matrix using for loop in python

I am kind new to python, and trying to create a dice example for CLT (central limit theory) as follows 我是python的新手,并尝试为CLT(中心极限理论)创建骰子示例,如下所示

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

SampleSize=1000000
NumberofDice=2

Dice=np.zeros([SampleSize,NumberofDice])

for i in range(NumberofDice+1):
 Dice[:,i]=np.random.randint(1,7,SampleSize)

but I had an error saying 但我说错了

Traceback (most recent call last): File "", line 11, in IndexError: index 2 is out of bounds for axis 1 with size 2 追溯(最近一次调用):文件“”,第11行,在IndexError中:索引2超出了大小为2的轴1的范围

I am not sure how to deal with it, basically I want to create a 2 X 1000000 matrix, and each row is an independent rolling dice process. 我不确定如何处理它,基本上我想创建一个2 X 1000000矩阵,并且每一行都是一个独立的滚动骰子过程。

Can anyone help? 有人可以帮忙吗?

range(NumberofDice+1) just remove that +1 , numpy indexing is 0 to n-1 , not 1 to n , and range also follows that convention. range(NumberofDice+1)只是删除+1 ,numpy的索引是0n-1而不是1nrange也遵循惯例。

By the way you could do it directly like so too: 顺便说一句,您也可以直接这样做:

Dice = np.random.randint(1,7,size=(SampleSize,NumberofDice))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM