Automatic reshape of two tensors when subtracting

Good afternoon,
I have two tensors of shape (n x k) and (k x m). What I want is to subtract each row of tensor_2 from tensor_1, so that the new array has a shape (n x k x m). Is it possible to do automatically without repeating the tensors m and n times respectively (as they consume much memory)?
Thanks in advance!

a = torch.tensor([10,20,30]).repeat(10).reshape(10,3) # n=10, k=3
b = torch.tensor([5,4,3,2,1]).repeat(3).reshape(3,5) #m=5
aT = a.unsqueeze(0) # adds a z-dimension
bTR = b.T.reshape(m, 1, k) 
result = aT - bTR # [m,n,k]

Thanks for the answer! However, I say this option is obvious but unfavorable due to the big amount of memory the tensors consume when repeated m and n times respectively.

The repeat calls are to emulate your input matrices. For the actual subtraction, you don’t need repeat, only these lines:

a = tensor_1
b = tensor_2
aT = a.unsqueeze(0) # adds a z-dimension
bTR = b.T.reshape(m, 1, k) 
result = aT - bTR # [m,n,k]
1 Like

That was exactly the point. Thank you, Suraj!