0

I'm trying to do multiplication of all the combination of elements in a certain dimension. For example, using for loops it would be

for a,i in enumerate(A):
    for b,j in enumerate(B):
        c[i][j] = a[1]*b[0]

not using for loop would be

A[:,None,1]*B[:,0] 

this worked fine for 2-dimensions(A.shape=(4,2),B.shape=(4,2)).

However, When I am expanding above procedures to 3-dimensions(A.shape=(2,4,2),B.shape=(2,4,2)).

I tried with

A[:,:,1]*B[:,:,None,0] 

but gives me an error.

How can I do this without using for loops???

For 2-dimensional tensors this is what I get

a = torch.FloatTensor([[0,1],[0,2],[0,3],[0,4]])
b = torch.FloatTensor([[1,0],[2,0],[3,0],[4,0]])
c = a[:,None,0] * b[:,1]

print(c)

tensor([[ 1.,  2.,  3.,  4.],
        [ 2.,  4.,  6.,  8.],
        [ 3.,  6.,  9., 12.],
        [ 4.,  8., 12., 16.]])

but in the case of

A = torch.cat([a.unsqueeze(0),a.unsqueeze(0)],dim=0)
B = torch.cat([b.unsqueeze(0),b.unsqueeze(0)],dim=0)


C = A[:,:,None,0] * B[:,:,1] << RuntimeError

RuntimeError: The size of tensor a (4) must match the size of tensor b (2) at non-singleton dimension 1

what I want is

tensor([[[ 1.,  2.,  3.,  4.],
         [ 2.,  4.,  6.,  8.],
         [ 3.,  6.,  9., 12.],
         [ 4.,  8., 12., 16.]],

        [[ 1.,  2.,  3.,  4.],
         [ 2.,  4.,  6.,  8.],
         [ 3.,  6.,  9., 12.],
         [ 4.,  8., 12., 16.]]])

I cannot think of a way to do this without using for loop in dimension 0.

Sukwon
  • 1
  • 1

0 Answers0