# Substract tensors with different sizes

Hi all!

this is probably somewhere in this forum’s history but I can’t seem to find it.

My problem is the following: I have two tensors containing each a list of 3D points, one is S of size (81,3) and the other P of size (20000, 3). What I’d like to do is to compute the “displacement” vectors D = S-P between every 3D point in P to every 3D point in S. So the resulting D vector would have dimensions (20000, 81, 3), i.e for every point in P there are 81 displacements.

Does anyone know how to do this efficiently in pytorch?

You could `unsqueeze` the tensors and let broadcasting do its job as seen here:

``````S = torch.arange(0, 5*3).view(5, 3)
P = torch.arange(1, 10*3+1).view(10, 3)

D = S.unsqueeze(0) - P.unsqueeze(1)
print(D.shape)
# > torch.Size([10, 5, 3])
print(D)
``````

Thanks for the prompt reply @ptrblck !

I was trying ‘repeat’ after the ‘unsqueeze’ to make them match in dimensions and then substract. It works but it looked unnecessary. This is more elegant.

Best