[英]Given two large numpy arrays, how to efficiently compute a matrix of a-b for any all (a,b) pair of the two arrays?
I have two large numpy arrays A, B. How can I efficiently (eg using numpy vectorization) compute a matrix C of shape len(A) * len(B) such that C[i,j]=A[i]- C[j]. I have two large numpy arrays A, B. How can I efficiently (eg using numpy vectorization) compute a matrix C of shape len(A) * len(B) such that C[i,j]=A[i]- C [j]。
For example, A is例如,A 是
a
b
c
B is乙是
d
e
f
g
Then expected C is然后预计 C 是
a-d a-e a-f a-g
b-d b-e b-f b-g
c-d c-e c-f c-g
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
A = np.tile(a.reshape(3,1),(1,3))
B = np.tile(b,(3,1))
C = A - B
print(A)
print(B)
print(C)
Yields:产量:
[[1 1 1]
[2 2 2]
[3 3 3]]
[[4 5 6]
[4 5 6]
[4 5 6]]
[[-3 -4 -5]
[-2 -3 -4]
[-1 -2 -3]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.