How to patch or add a tensor to a bigger tensor?

I have two tensors, each size of (3x3), (5x5).

How can I add or assign a smaller tensor to a bigger tensor starting from a specific position?

Ex)
A is a zero tensor size of (5x5).
B is a tensor, all valued with 1.

Then, I want to make C as below.

(1)
[[0, 0, 1, 1, 1],
[0, 0, 1, 1, 1],
[0, 0, 1, 1, 1],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]

Or

(2)
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[1, 1, 1, 0, 0],
[1, 1, 1, 0, 0],
[1, 1, 1, 0, 0]]

1 Like

You could just index the bigger tensor and assign the smaller one to these positions:

a = torch.zeros(5, 5)
a[2:, 2:] = torch.ones(3, 3)
4 Likes