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]])
I have a block_2 offset in the coordinate system of block_1 element.
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 the long run, I would like to quickly add two different forms of the matrix, where one of the matrices can be shifted. The resulting matrix must be in the form of the first matrix, and the overlapping elements between the two matrices are added up. If there is no overlap, only the first matrix returns without mutation.
I have a function that works fine, but it looks ugly, and in different ways:
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
Can a broadcast or cut do this?
I feel that maybe I am missing something obvious.