如何比较两个矩阵的每个元素

我想比较具有相同维度的两个矩阵的每个元素。我想知道,第一个矩阵中的一个元素是否小于第二个矩阵中具有相同索引的另一个元素。我想用第一个矩阵的值填充第三个矩阵,但是适用我的标准的每个条目都应该是 0。下面我将展示我的方法:


a = ([1, 2, 3], [3, 4, 5], [5, 6, 7])

b = ([2, 3, 1], [3, 5, 4], [4, 4, 4])


c = np.zeros(a.shape)


for i, a_i in enumerate(a):

    a_1 = a_i

    for i, b_i in enumerate(b):

        b_1 = b_i

        if a_1 < b_1:

            c[i] = 0

        else:

            c[i] = a_1


如果我在这里犯了任何简单的错误,我很抱歉,但我对 python很陌生。我发现了一些关于如何查找匹配条目的帖子,但我不知道是否有可以使用该方法的解决方案。我很感激任何帮助,谢谢。


慕标琳琳
浏览 211回答 2
2回答

MM们

就我个人而言,我发现仅使用索引来遍历矩阵更容易:a = ([1, 2, 3], [3, 4, 5], [5, 6, 7])b = ([2, 3, 1], [3, 5, 4], [4, 4, 4])c = ([0, 0, 0], [0, 0, 0], [0, 0, 0])for i in range(len(a)):&nbsp; &nbsp; for j in range(len(a[0])):&nbsp; &nbsp; &nbsp; &nbsp; if a[i][j] < b[i][j]:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c[i][j] = 0&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c[i][j] = a[i][j]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;如果使用索引循环 a 和 b,则可以访问 c 中的相同位置。i 索引跟踪您所在的列表(即,a 中索引 0 处的列表是 [1, 2, 3],b 中索引 0 处的列表是 [2, 3, 1])。j 索引跟踪您所在的每个列表的哪个元素(即,a 中索引 0 处的列表中的元素 0 为 1,b 中索引 0 处的列表中的元素 0 为 2)。这样您就可以直接访问 3 个矩阵中任意一个的任意元素。此外,由于 c 中的每个元素都以 0 开头,因此当 a 中的元素小于 b 中的元素时,您不需要将其重新分配为 0,因此您可以简化 if/else 语句,只需执行以下操作即可if a[i][j] >= b[i][j]:&nbsp; &nbsp; c[i][j] = a[i][j]

PIPIONE

我真的很喜欢您的解决方案和反馈,非常感谢您!然而,与此同时,我自己找到了一个解决方案(我将只输入我使用的循环):for i, a_i in enumerate(a):&nbsp; &nbsp; a_1 = a_i&nbsp; &nbsp; c = a_1&nbsp; &nbsp; for i, b_i in enumerate(b):&nbsp; &nbsp; &nbsp; &nbsp; b_1 = b_i&nbsp; &nbsp; &nbsp; &nbsp; c[np.where(c < b_1)] = np.nan您认为计算更快的解决方案是什么?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python