使用掩码提取内部节点时触发ValueError问题求助
问题原因与解决方法
错误根源
你创建的mask是二维数组(形状(1, nn)),当执行mask[k]时,得到的不是单个布尔值,而是一个长度为1的一维数组(例如array([True]))。numpy不允许直接在if条件中判断数组的布尔值——因为它无法确定你是要求数组所有元素为真,还是至少一个元素为真,因此抛出ValueError。
解决方法
方法1:创建一维掩码(推荐)
直接将mask定义为一维数组,这样mask[k]会直接返回单个标量布尔值,消除歧义:
def SortedInteriorNodes(p,e,t): # e is a matrix with two rows, p a matrix with 2 rows, t a matrix with 3 rows nn=p.shape[1] # number of nodes nt=t.shape[1] # number of triangles ne=e.shape[1] # number of edges = number of boundary nodes nodes = np.arange(start=0, stop=nn) # 0 1 2 3 ....np-1 # 创建一维掩码,而非(1, nn)的二维数组 mask = np.full(nn, True) for col in range(ne): for row in range(2): k = e[row, col] if mask[k]: # 直接判断布尔值,无需==True mask[k] = False InteriorNodes = nodes[mask] return InteriorNodes
方法2:保留二维掩码时正确取值
如果一定要用二维掩码,需要通过mask[0, k]取到单个标量值:
if mask[0, k] == True: mask[0, e[row,col]] = False
更高效的numpy写法(替代循环)
numpy支持向量化操作,完全不需要嵌套循环,代码更简洁高效:
def SortedInteriorNodes(p,e,t): nn = p.shape[1] # 提取所有边界节点并去重 boundary_nodes = np.unique(e.flatten()) # 创建一维掩码 mask = np.full(nn, True) # 批量将边界节点对应掩码设为False mask[boundary_nodes] = False # 提取内部节点 return np.arange(nn)[mask]
内容的提问来源于stack exchange,提问作者some_math_guy
相关产品推荐
相关产品推荐

