# How could I mix two tensor at variable place and size?

Hi,

I am trying to do this:

``````a = torch.randn(4, 3, 10, 10)
b = torch.randn(4, 3, 10, 10)
x1 = torch.randint(0, 5, (4,))
y1 = torch.randint(0, 5, (4,))
x2 = torch.randint(6, 10, (4,))
y2 = torch.randint(6, 10, (4,))

b[:, :, x1:x2, y1:y2] = a[:, :, x1:x2, y1:y2]
``````

This gives the error message of

TypeError: only integer tensors of a single element can be converted to an index

How could I make it work please ?

What are you trying to do?
You are using indexing over a tuple…

Hi,

My tensors of a and b have size of (N, C, H, W) and I want to crop (h, w) crops from tensor a and patch it to the associated positions to tensor b. The problem is the I defined N different (h, w) patches which has different positions and sizes. That means I need to copy a[0, :, h0_0:h0_1, w0_0, w0_1] to b[0, :, h0_0:h0_1, w0_0, w0_1], and copy a[1, :, h1_0, h1_1, w1_0:w1_1] to b[1, :, h1_0, h1_1, w1_0:w1_1], and a[2, :, h2_0:h2_1, w2_0:w2_1] to b[2, :, h2_0:h2_1, w2_0:w2_1], and so on.

Would you please tell me how can I do this with pytorch ?

Hmmm I don’t really know if it’s possible to do it in a single line.

Typically (here and in numpy) when you pass a list for indexing it means “gather elements in those indices”

For example:

``````a[[0,2,3],1:5,3:8]
``````

would get [1:5,3:8] for elements 0,2,3.

In your case however it’s more like doing a for loop together with indexing.

Soo you could do something like

``````import numpy as np
x = np.array([[ 0,  1,  2],[ 3,  4,  5],[ 6,  7,  8],[ 9, 10, 11]])

print 'Our array is:'
print x
print '\n'

rows = np.array([[0,0],[3,3]])
cols = np.array([[0,2],[0,2]])
y = x[rows,cols]

print 'The corner elements of this array are:'
print y
``````
``````Our array is:
[[ 0  1  2]
[ 3  4  5]
[ 6  7  8]
[ 9 10 11]]

The corner elements of this array are:
[[ 0  2]
[ 9 11]]
``````

(From numpy’s examples)
And passing a matrix which get indices element-wise but it would be a bit messy compared to a for loop

``````import torch

N = 4
a = torch.randn(N, 3, 10, 10)
b = torch.randn(N, 3, 10, 10)
X1 = torch.randint(0, 5, (N,))
Y1 = torch.randint(0, 5, (N,))
X2 = torch.randint(6, 9, (N,))
Y2 = torch.randint(6, 9, (N,))

for i,(x1,y1,x2,y2) in enumerate(zip(X1,Y1,X2,Y2)):

b[i, :, x1:x2, y1:y2] = a[i, :, x1:x2, y1:y2]
``````
1 Like