添加不同大小/形状的置换NumPy矩阵 [英] Adding different sized/shaped displaced NumPy matrices

查看:157
本文介绍了添加不同大小/形状的置换NumPy矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简而言之:我有两个矩阵(或数组):

In short: I have two matrices (or arrays):

import numpy

block_1 = numpy.matrix([[ 0, 0, 0, 0, 0],
                        [ 0, 0, 0, 0, 0],
                        [ 0, 0, 0, 0, 0],
                        [ 0, 0, 0, 0, 0]])

block_2 = numpy.matrix([[ 1, 1, 1],
                        [ 1, 1, 1],
                        [ 1, 1, 1],
                        [ 1, 1, 1]])

block_1元素坐标系中有block_2的位移.

I have the displacement of block_2 in the block_1 element coordinate system.

pos = (1,1)

我希望能够(快速)添加它们以获得:

I want to be able to add them (quickly), to get:

[[0 0 0 0 0]
 [0 1 1 1 0]
 [0 1 1 1 0]
 [0 1 1 1 0]]

很长一段时间:我想用一种快速的方法将两个不同形状的矩阵加在一起,其中一个矩阵可以移动.所得矩阵必须具有第一个矩阵的形状,并且将两个矩阵之间的重叠元素相加.如果没有重叠,则只返回第一个矩阵不变.

In long: I would like a fast way to add two different shape matrices together, where one of the matrices can be displaced. The resulting matrix must have the shape of the first matrix, and the overlapping elements between the two matrices are summed. If there is no overlap, just the first matrix is returned unmutated.

我有一个可以正常工作的函数,但它有点丑陋,而且是逐元素的:

I have a function that works fine, but it's kind of ugly, and elementwise:

def add_blocks(block_1, block_2, pos):
    for i in xrange(0, block_2.shape[0]):
        for j in xrange(0, block_2.shape[1]):
            if (i + pos[1] >= 0) and (i + pos[1] < block_1.shape[0])
               and (j + pos[0] >= 0) and (j + pos[0] < block_1.shape[1]):
                block_1[pos[1] + i, pos[0] + j] += block_2[i,j]
    return block_1

可以广播或切片吗?

我觉得我可能遗漏了一些明显的东西.

I feel like maybe I'm missing something obvious.

推荐答案

您只需要找到重叠范围,然后使用切片添加数组即可.

You just have to find the overlapping range, and then add the arrays using slicing.

b1 = np.zeros((4,5))
b2 = np.ones((4,3))
pos_v, pos_h = 2, 3  # offset
v_range1 = slice(max(0, pos_v), max(min(pos_v + b2.shape[0], b1.shape[0]), 0))
h_range1 = slice(max(0, pos_h), max(min(pos_h + b2.shape[1], b1.shape[1]), 0))

v_range2 = slice(max(0, -pos_v), min(-pos_v + b1.shape[0], b2.shape[0]))
h_range2 = slice(max(0, -pos_h), min(-pos_h + b1.shape[1], b2.shape[1]))

b1[v_range1, h_range1] += b2[v_range2, h_range2]

它们是就地添加的,但是您也可以创建一个新的数组.我可能已经错过了一些极端情况,但是它似乎可以正常工作.

They're added in-place, but you could also create a new array. I might have missed some corner cases, though, but it seems to work fine.

这篇关于添加不同大小/形状的置换NumPy矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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