首页 > 解决方案 > 矩阵内的圆圈

问题描述

我正在尝试建立一个统计模型,该模型将检测与方差锥内的杆相互作用的可能性。

我已经设法在矩阵中创建了圆,但我想区分圆的内部和外部。有没有一种方法可以使圆函数之外的所有内容成为单独的值?

这是我到目前为止所拥有的:

import numpy as np  
import matplotlib.pyplot as plt

def my_unit_circle(r):  
   d = 2*r + 1  
   rx, ry = d/2, d/2  
   x, y = np.indices((d, d))  
   return (np.abs(np.hypot(rx - x, ry - y)-r) < 0.5).astype(int)

model = my_unit_circle(300)

model[300:325,0:600] = 2

plt.matshow(model)  
plt.show()'''

这给了我这个:

Matshow 图像

预先感谢您的任何帮助。

标签: pythonnumpymatplotlib

解决方案


np.where可用于根据条件创建具有值的数组:

import numpy as np
import matplotlib.pyplot as plt

def my_unit_circle(r):
   d = 2*r + 1
   rx, ry = d/2, d/2
   x, y = np.indices((d, d))
   return np.where(np.hypot(rx - x, ry - y) < r,  1, 0)

model = my_unit_circle(300)

model[300:325,0:600] = 2

plt.matshow(model)
plt.show()

结果图


推荐阅读