开发者

generate a patterned numpy matrix

开发者 https://www.devze.com 2023-04-09 02:44 出处:网络
Is it possible to generate a nump开发者_运维问答y matrix with a circular pattern of \"1\"s in a rest matrix of \"0\"s? So basically a

Is it possible to generate a nump开发者_运维问答y matrix with a circular pattern of "1"s in a rest matrix of "0"s? So basically a

generate(ysize, xsize, ycenter, xcenter, radius)

Should look something like

[000000000]
[000000000]
[000001000]
[000011100]
[000111110]
[000011100]
[000001000]
[000000000]

(ok this looks stupid but on a 1000x1000 scale it would make sense)

Is there such a possibility in numpy?


def generate(ysize, xsize, ycenter, xcenter, radius):
    x = np.arange(xsize)[None,:]
    y = np.arange(ysize)[:,None]
    return ((xcenter - x) ** 2 + (ycenter - y) ** 2 <= radius ** 2) * 1


generate(10,8,4,3,2)


array([[0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 1, 1, 1, 0, 0, 0],
       [0, 1, 1, 1, 1, 1, 0, 0],
       [0, 0, 1, 1, 1, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0]])


A little more concisely than @eumiro's answer, but essentially the same.

import numpy

def generate(ysize, xsize, ycenter, xcenter, radius):
    x, y = numpy.mgrid[0:ysize,0:xsize]
    return ((x - ycenter)**2 + (y - xcenter)**2 <= radius**2) * 1
0

精彩评论

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

关注公众号