简体   繁体   English

计算来自(矩阵 - 常数)的矩阵的快速方法

[英]Fast way to compute matrix of the from (Matrix - constant)

I would like to find a faster way to compute the matrix v .我想找到一种更快的方法来计算矩阵v Note that if height = width then the matrix v is symmetric, v = vT .请注意,如果 height = width 那么矩阵 v 是对称的, v = vT The width and the height are arbitrary positive integers.宽度和高度是任意正整数。

v = np.zeros((height, width)) # rows columns

# region center
cr = np.round(height / 2)
cc = np.round(width / 2)

# there has to be a quicker way to do this
for w in range(width):
    v[:, w] = [np.sqrt((w - cc) ** 2 + (h - cr) ** 2) for h in range(height)]

You can simplify this by using numpy's broadcasting :您可以通过使用 numpy 的 广播来简化这一点:

out = np.sqrt((np.arange(width)-cc)**2 + (np.arange(height)[:,None]-cr)**2) 

width=5
height=8
v = np.zeros((height, width)) # rows columns
# region center
cr = np.round(height / 2)
cc = np.round(width / 2)
# there has to be a quicker way to do this
for w in range(width):
    v[:, w] = [np.sqrt((w - cc) ** 2 + (h - cr) ** 2) for h in range(height)]

np.allclose(v, out)
# True

You can use scipy.spatial.distance.cdist , with numpy.indices :您可以使用scipy.spatial.distance.cdistnumpy.indices

from scipy.spatial.distance import cdist
import numpy as np

shape = (height, width)
v = cdist(np.indices(shape).reshape(2, -1).T, [[cr, cc]]).reshape(shape)

This yields identical results to @yatu's broadcasting solution in all cases, but strangely is ~3x slower for a large variety of input sizes.这在所有情况下都与@yatu 的广播解决方案产生了相同的结果,但奇怪的是,对于各种输入大小来说慢了约 3 倍。 That being said, it is likely a bit more space efficient, since it allocates only one array of the output size rather than two (second one being the sum fed into the square root).话虽如此,它可能更节省空间,因为它只分配一个 output 大小的数组,而不是两个(第二个是输入平方根的总和)。 This should not be a consideration for any normal input you encounter, so use the broadcasting solution.这不应该是您遇到的任何正常输入的考虑因素,因此请使用广播解决方案。 This is just here for completeness.这只是为了完整性。

You can do this without any loop.您可以在没有任何循环的情况下执行此操作。 Generate a matrix of row indexes and a matrix of column indexes and apply the formula between the two matrices:生成行索引矩阵和列索引矩阵,并在两个矩阵之间应用公式:

rows,cols = np.indices((height,width))
v         = np.sqrt((rows-height//2)**2+(cols-width//2)**2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM