I have two Tensors A and B,

A.shape is (b,c,100,100),

B.shape is (b,c,80,80),

how can I get tensor C with shape (b,c,21,21) subject to

C[:, :, i, j] = torch.mean(A[:, :, i:i+80, j:j+80] - B)?

I wonder whether there’s an efficient way to solve this?

Thanks very much.

Sorry if it’s not a proper title.

If I understand you correctly, would it be the way to subtract B from part of A?

You can specify corresponding index ranges if the dimension lengths equal to each other.

```
C = A[:,:,80:100, 80:100] - B
# C shape: b x c x 20 x 20
```

You can further apply `torch.mean`

afterwards by your needs.

Appreciate for your reply. But you did misunderstand my question.

I hope B to be a filter, do torch.mean(slice_A - B), and slide B to next position, etc. And the result would has shape (b, c, A.shape[-1] - B.shape[-1] + 1, A.shape[-1] - B.shape[-1] + 1).

Ah, sorry for the misunderstanding.

You can try below.

```
C = (A.unfold(2,80,1).unfold(3,80,1) - B.expand(b,c,21,21,80,80)).mean(dim=(-2,-1))
# variable version
_, _, H, W = A.shape
_, _, h, w = B.shape
C = (A.unfold(2,h,1).unfold(3,w,1) - B.expand(b,c,H-h+1,W-w+1,h,w)).mean(dim=(-2,-1))
```

The keys are torch.Tensor.unfold and torch.Tensor.expand.

The unfold function extracts sliding window and expand function views the tensor in expanded size without copying values.

I asked the same question on stackoverflow. https://stackoverflow.com/questions/64313895/element-wise-operation-in-pytorch