# How to operate torch.dot() in matrix consist of vectors in pytorch?

I have tensor like this:

``````arr1 = np.array([[ 1.6194, -0.6058, -0.8012], [ 1.1483,  1.6538, -0.8062]])
arr2 = np.array([[-0.3180, -1.8249,  0.0499], [-0.4184,  0.6495, -0.4911]])
X = torch.Tensor(arr1)
Y = torch.Tensor(arr2)
``````

I want to do torch.dot on every tensor 1D (2 vectors) inside my 2D tensor

``````torch.dot(X, Y)
``````

I want to get the result like this tensor([dotResult1, dotResult2]).
But I got the error like this:

``````RuntimeError: 1D tensors expected, but got 2D and 2D tensors
``````

My main purpose is to do â€śsomethingâ€ť operation on every vector inside my matrix but I donâ€™t want to use looping here, does anyone know how to do that?

Hi Ellipsis â€¦

This will depend on what â€śsomethingâ€ť is. In general, you would want to
figure out how to do â€śsomethingâ€ť using pytorch tensor operations that act
on your 2D tensors all at once.

For your particular example of computing the dot products of the vectors
in your 2D tensors you can use element-wise multiplication and then sum
the rows or, equivalently, use the general purpose einsum() to do the same
thing:

``````>>> import torch
>>> torch.__version__
'1.12.0'
>>> X = torch.tensor ([[ 1.6194, -0.6058, -0.8012], [ 1.1483,  1.6538, -0.8062]])
>>> Y = torch.tensor ([[-0.3180, -1.8249,  0.0499], [-0.4184,  0.6495, -0.4911]])
>>> resultA = (X * Y).sum (dim = 1)
>>> resultA
tensor([0.5506, 0.9896])
>>> resultB = torch.einsum ('ij, ij -> i', X, Y)
>>> torch.equal (resultA, resultB)
True
``````

(As youâ€™ve noticed, pytorch does not offer a specific â€śbatch-vector-dot-productâ€ť
function â€“ not that it needs one.)

Best.

K. Frank

1 Like

Thank you itâ€™s work!