1

I have two tensors a and b which are of different dimensions. a is of shape [100,100] and b is of the shape [100,3,10]. I want to concatenate these two tensors. For example:

a = torch.randn(100,100)
tensor([[ 1.3236,  2.4250,  1.1547,  ..., -0.7024,  1.0758,  0.2841],
        [ 1.6699, -1.2751, -0.0120,  ..., -0.2290,  0.9522, -0.4066],
        [-0.3429, -0.5260, -0.7748,  ..., -0.5235, -1.8952,  1.2944],
        ...,
        [-1.3465,  1.2641,  1.6785,  ...,  0.5144,  1.7024, -1.0046],
        [-0.7652, -1.2940, -0.6964,  ...,  0.4661, -0.3998, -1.2428],
        [-0.4720, -1.0981, -2.3715,  ...,  1.6423,  0.0560,  1.0676]])

The tensor b is as follows:

tensor([[[ 0.4747, -1.9529, -0.0448,  ..., -0.9694,  0.8009, -0.0610],
         [ 0.5160,  0.0810,  0.1037,  ..., -1.7519, -0.3439,  1.2651],
         [-0.5975, -0.2000, -1.6451,  ...,  1.3082, -0.4023, -0.3105]],
        ...,

        [[ 0.4747, -1.9529, -0.0448,  ..., -0.9694,  0.8009, -0.0610],
         [ 0.1939,  1.0365, -0.0927,  ..., -2.4948, -0.2278, -0.2390],
         [-0.5975, -0.2000, -1.6451,  ...,  1.3082, -0.4023, -0.3105]]],
       dtype=torch.float64, grad_fn=<CopyBackwards>)

I want to concatenate such that the first row in tensor a of size [100] is concatenated with the first row in tensor b which is of size [3,10]. This should be applicable to all rows in both tensors. That is, in simple words, considering just the first row in a and b, I want to get an output with size [100,130] as follows:

[ 1.3236,  2.4250,  1.1547,  ..., -0.7024,  1.0758,  0.2841, 0.4747, -1.9529, -0.0448,  ..., -0.9694,  0.8009, -0.0610, 0.5160,  0.0810,  0.1037,  ..., -1.7519, -0.3439,  1.2651, -0.5975, -0.2000, -1.6451,  ...,  1.3082, -0.4023, -0.3105]

In order to do this, I performed unsqueezed to tensor a to get the two tensors in the same dimensions as follows.

a = a.unsqueeze(1)

When I perform torch.cat([a,b], I still get an error. Can somebody help me in solving this?

Thanks in advance.

2
  • what is the expected output size? Commented Dec 20, 2021 at 11:53
  • The expected output size is [100,130]. Commented Dec 20, 2021 at 12:09

1 Answer 1

3

Reshape b tensor accordingly and then merge it to a using torch.cat on 1 dim

torch.cat((a, b.reshape(100, -1)), dim=1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.