从两个数组中减去所有成对的值 [英] Subtract all pairs of values from two arrays

查看:74
本文介绍了从两个数组中减去所有成对的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个向量,v1v2.我想从每个v1的值中减去每个v2的值,并将结果存储在另一个向量中.我还想使用非常大的向量(例如1e6大小),因此我认为我应该使用numpy来提高性能.

I have two vectors, v1 and v2. I'd like to subtract each value of v2 from each value of v1 and store the results in another vector. I also would like to work with very large vectors (e.g. 1e6 size), so I think I should be using numpy for performance.

到目前为止,我有:

import numpy
v1 = numpy.array(numpy.random.uniform(-1, 1, size=1e2))
v2 = numpy.array(numpy.random.uniform(-1, 1, size=1e2))
vdiff = []
for value in v1:
    vdiff.extend([value - v2])

这将创建一个包含100个条目的列表,每个条目都是大小为100的数组.尽管如此,我不知道这是否是最有效的方法. 我想以最小的对象大小(在内存上)非常快地计算1e4期望值.

This creates a list with 100 entries, each entry being an array of size 100. I don't know if this is the most efficient way to do this though. I'd like to calculate the 1e4 desired values very fast with the smallest object size (memory wise) possible.

推荐答案

您不会对提到的巨型数组有太多的兴趣.但是,如果您有大小合适的矩阵(足够小以使结果适合内存),最好的方法是使用

You're not going to have very much fun with the giant arrays that you mentioned. But if you have more reasonably-sized matrices (small enough that the result can fit in memory), the best way to do this is with broadcasting.

import numpy as np

a = np.array(range(5, 10))
b = np.array(range(2, 6))

res = a[np.newaxis, :] - b[:, np.newaxis]
print(res)
# [[3 4 5 6 7]
#  [2 3 4 5 6]
#  [1 2 3 4 5]
#  [0 1 2 3 4]]

这篇关于从两个数组中减去所有成对的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆