具有类似矩阵输出的一维数组的成对计算 [英] Pairwise calculation on a 1D-Array with Matrix-like output

查看:54
本文介绍了具有类似矩阵输出的一维数组的成对计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有以下一维数组:

Assume you have the following 1D-Array:

array([1,2,3,4,5])

我想在每个数字组合(如加法、减法等)之间执行不同(简单)的计算,得到一个矩阵类型的输出(没有重复),即对于上面的数组,输出应该是下面如果我们想计算成对差异:

I want to perform different (simple) calculations between each combination of numbers (such as addition, subtraction, etc.) resulting in a Matrix-type output (without duplication), i.e. for the above array, the output should be as below if we wanted to calculated the pairwise difference:

array([0,-,-,-,-],            
      [1,0,-,-,-],
      [2,1,0,-,-],
      [3,2,1,0,-],
      [4,3,2,1,0]) 

当然可以对两个 for 循环使用蛮力,但我觉得有更好的方法,我似乎找不到正确的方法.

Of course one could use brute force with two for loops but I feel like there is a better way, I just can't seem to find the right method.

推荐答案

利用 numpy 广播来计算成对差异.像这样不需要循环.为此,必须在同一数组的行向量和列向量之间进行操作.

Make use of numpy broadcasting to calculate the pairwise difference. Like this no loops are needed. For that to happen the operation has to be done between a row- and a column-vector of the same array.

import numpy as np
x = np.arange(1,6, dtype=np.float)

# x[:,None] adds a second axis to the array
mat = x[:,None]-x

这产生:

array([[ 0., -1., -2., -3., -4.],
       [ 1.,  0., -1., -2., -3.],
       [ 2.,  1.,  0., -1., -2.],
       [ 3.,  2.,  1.,  0., -1.],
       [ 4.,  3.,  2.,  1.,  0.]])

这篇关于具有类似矩阵输出的一维数组的成对计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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