coo*_*kie 4 python matlab numpy matrix
嘿家伙所以我试图在python中重写以下matlab代码:
repmat(points, 1, length(points)) - repmat(points', length(points),1);
Run Code Online (Sandbox Code Playgroud)
points 是一个包含几个点的弧度值的数组.
上面的代码给我一个像这样的矩阵输出:
0 1 2 0 1 2 0 1 2
-1 0 1 -1 0 1 -1 0 1
-2 -1 0 -2 -1 0 -2 -1 0
0 1 2 0 1 2 0 1 2
-1 0 1 -1 0 1 -1 0 1
-2 -1 0 -2 -1 0 -2 -1 0
0 1 2 0 1 2 0 1 2
-1 0 1 -1 0 1 -1 0 1
-2 -1 0 -2 -1 0 -2 -1 0
Run Code Online (Sandbox Code Playgroud)
我可以轻松地操纵以获得从每个点到每个其他点的距离.
我只是想知道是否有使用numpy的单行方式吗?
我尝试了以下哪些不起作用:
np.tile(points, (1, len(points))) -
np.tile(points.T, (len(points), 1))
Run Code Online (Sandbox Code Playgroud)
有人有什么想法吗?
在MATLAB中,您必须使用,repmat因为您需要在左侧和右侧的数组-具有相同的大小.有了numpy,由于numpy的自动广播,情况并非如此.相反,您可以简单地从另一个中减去一个,自动广播将创建预期大小的结果.
# Create some example data
points = np.array([[1,2,3,4]]);
# Just subtract the transpose from points
B = points - points.T
# array([[ 0, 1, 2, 3],
# [-1, 0, 1, 2],
# [-2, -1, 0, 1],
# [-3, -2, -1, 0]])
Run Code Online (Sandbox Code Playgroud)
如果points只是一维数组,那么@JoshAdel的答案应该适用于你(也使用广播),或者你可以将它转换为2D数组.