-1

I have a tensor A of size torch.Size([3]) and another tensor B of size torch.Size([4,3]).

I want to find the distance between A and each of the 4 rows of B.

I'm new to Torch and I reckon a for loop for each of the rows wouldn't be efficient. I have looked into torch.linalg.norm and torch.cdist but I'm not sure if they solve my problem, unless I'm missing something.

dsplnme
  • 3
  • 1
  • 1
  • 3
    Please provide a [mre] including a specific problem and the code you've tried. Both `torch.cdist(B, A.unsqueeze(0))` and `torch.linalg.norm(B - A, dim=1, keepdim=True)` are efficient solutions. – Michael Szczesny Sep 11 '22 at 16:47
  • 1
    Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 12 '22 at 06:01

1 Answers1

1

You look for:

torch.norm(A[None, :] - B, p=2, dim=1)
  • A[None, :] resize the tensor to shape (1, 3)
  • A[None, :] - B will copy 4 times the tensor A to match the size of B ("broadcast") and make the substraction
  • torch.norm(..., p=2, dim=1) computes the euclidian norme for each column.

Output shape: (4,)

Valentin Goldité
  • 1,040
  • 4
  • 13