开发者

From for loops to numpy dot implementation

开发者 https://www.devze.com 2023-03-09 08:37 出处:网络
N=100 reliab=zeros((N,N)) for i in range(N): for j in range(N): if random() < 0.6: reliab[i,j] = 1 else:
N=100 

reliab=zeros((N,N))


for i in range(N):    

    for j in range(N):
        if random() < 0.6:
            reliab[i,j] = 1
        else:
            reli开发者_JAVA百科ab[i,j] = 0

As in my code this matrix filling is recalled a huge number of times, these for loops should be changed with a dot product...but I dunno how to do it... Anyone willing to help me?


I'm not sure I understand your problem completely, but the following line should be doing the same thing as your code:

reliab = numpy.int32(numpy.random.rand(N,N) < 0.6)


>>> import numpy as np
>>> reliab = np.random.random((N,N))
>>> reliab = reliab < 0.6
>>> reliab.dtype = np.int8
>>> reliab
array([[0, 0, 0, ..., 1, 0, 1],
       [0, 1, 1, ..., 0, 1, 0],
       [1, 1, 0, ..., 1, 0, 1],
       ..., 
       [0, 1, 0, ..., 1, 1, 1],
       [0, 0, 1, ..., 1, 1, 1],
       [0, 1, 0, ..., 0, 0, 0]], dtype=int8)
0

精彩评论

暂无评论...
验证码 换一张
取 消