英文:
How do I replace my nested for loop with broadcasting?
问题
可以使用广播(broadcasting)来替代嵌套的for循环,以实现不同方式的矩阵元素交互。希望避免嵌套for循环的话,可以使用NumPy库来进行广播操作。
以下是使用广播重写的代码:
import numpy as np
values = np.array([[33, 23, 0.6, 0.8, 1.5], [34, 25, 0.9, 0.7, 1.6]])
points = np.array([[0.2, 19.8], [0.6, 19.8]])
# 使用广播计算差值
pa_x = values[:, 0] - points[:, 0][:, np.newaxis]
pa_y = values[:, 1] - points[:, 1][:, np.newaxis]
这个代码片段使用NumPy数组来执行广播操作,将values
和points
两个不同大小的矩阵的元素进行不同方式的交互,同时避免了嵌套的for循环。
英文:
I have two different matrices of unequal sizes and I want each element in one matrice to interact with the second matrice differently. Can I replace the nested for-loops with broadcasting? I want to ideally avoid a nested for loop.
values=[[33,23,0.6,0.8,1.5],[34,25,0.9,0.7,1.6]]
points=[[0.2,19.8],[0.6,19.8]]
for i in points:
for j in values:
pa_x = j[0]-i[0]
pa_y = j[1]-i[1]
答案1
得分: 1
在这种情况下,您可以使用广播替代嵌套的for循环。广播是NumPy中的一个强大功能,允许您在不同形状的数组之间执行逐元素操作。
import numpy as np
values = np.array([[33, 23, 0.6, 0.8, 1.5], [34, 25, 0.9, 0.7, 1.6]])
points = np.array([[0.2, 19.8], [0.6, 19.8]])
# 使用广播从values中减去points
pa_x = values[:, 0] - points[:, 0][:, np.newaxis]
pa_y = values[:, 1] - points[:, 1][:, np.newaxis]
np.newaxis 用于为 points[:, 0] 和 points[:, 1] 添加新的轴,以便在从 values[:, 0] 和 values[:, 1] 减去时可以正确广播它们。
运行此代码后,pa_x 和 pa_y 将包含values中每个元素与points中每个元素之间的差异,而无需使用嵌套的for循环。
英文:
You can replace the nested for loop with broadcasting in this case. Broadcasting is a powerful feature in NumPy that allows you to perform element-wise operations between arrays of different shapes.
import numpy as np
values = np.array([[33, 23, 0.6, 0.8, 1.5], [34, 25, 0.9, 0.7, 1.6]])
points = np.array([[0.2, 19.8], [0.6, 19.8]])
# Broadcasting to subtract points from values
pa_x = values[:, 0] - points[:, 0][:, np.newaxis]
pa_y = values[:, 1] - points[:, 1][:, np.newaxis]
np.newaxis is used to add a new axis to points[:, 0] and points[:, 1], so that they can be broadcasted properly when subtracted from values[:, 0] and values[:, 1], respectively.
After running this code, pa_x and pa_y will contain the differences between each element in values and each element in points, without using a nested for loop.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论