首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python函数可以快速比较矩阵的值吗?

Python函数可以快速比较矩阵的值吗?
EN

Stack Overflow用户
提问于 2022-09-23 20:24:36
回答 2查看 61关注 0票数 -1

很抱歉,我问了一个基本的问题,但我一直在做一个信号分析项目,我们需要为这个项目分配一个变量,一个象限的值集(n维向量)位于哪个象限中。作为一名生物医学工程师,我一直在努力寻找更有效或更“漂亮”的解决方案。目前,我为三维向量工作的方式是做多个比较:

代码语言:javascript
运行
复制
if (ondas[0]>0)&(ondas[1]>0)&(ondas[2]>0):
    note=1
elif (ondas[0]>0)&(ondas[1]>0)&(ondas[2]<0):
    note=2
elif (ondas[0]>0)&(ondas[1]<0)&(ondas[2]<0):
    note=3
elif (ondas[0]<0)&(ondas[1]<0)&(ondas[2]<0):
    note=4
elif (ondas[0]<0)&(ondas[1]>0)&(ondas[2]<0):
    note=5
elif (ondas[0]<0)&(ondas[1]<0)&(ondas[2]>0):
    note=6
elif (ondas[0]<0)&(ondas[1]>0)&(ondas[2]>0):
    note=7
elif (ondas[0]>0)&(ondas[1]<0)&(ondas[2]>0):
    note=8
else:
    note=0

其中ondas是我的数组,有3个值。这段代码运行得很好,但我想知道是否还有其他方法来解决这个问题。我在这个解决方案上已经做得够好了,但我愿意听取关于这个问题的反馈意见。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-09-23 20:36:39

有许多不同的方法来处理这个问题。最简单的方法可能是为每个轴创建一个布尔值,并将每个配置的象限存储在字典中。这与你所做的基本相同,只是更短、更清晰:

代码语言:javascript
运行
复制
axis_to_quad = {(0, 0, 0): 1,
                (0, 0, 1): 2,
                (0, 1, 1): 3,
                (1, 1, 1): 4,
                (1, 0, 1): 5,
                (1, 1, 0): 6,
                (1, 0, 0): 7,
                (0, 1, 0): 8}

note = axis_to_quad[(ondas[0] < 0, ondas[1] < 0, ondas[2] < 0)]
票数 2
EN

Stack Overflow用户

发布于 2022-09-23 20:53:44

没有真正改变您的逻辑,而是用&替换为and,去掉了大量的父类,添加了一些空格,并使用了一个条件表达式。

代码语言:javascript
运行
复制
note = 1 if ondas[0] > 0 and ondas[1] > 0 and ondas[2] > 0 else \
       2 if ondas[0] > 0 and ondas[1] > 0 and ondas[2] < 0 else \
       3 if ondas[0] > 0 and ondas[1] < 0 and ondas[2] < 0 else \
       4 if ondas[0] < 0 and ondas[1] < 0 and ondas[2] < 0 else \
       5 if ondas[0] < 0 and ondas[1] > 0 and ondas[2] < 0 else \
       6 if ondas[0] < 0 and ondas[1] < 0 and ondas[2] > 0 else \
       7 if ondas[0] < 0 and ondas[1] > 0 and ondas[2] > 0 else \
       8 if ondas[0] > 0 and ondas[1] < 0 and ondas[2] > 0 else \
       9 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73832661

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档