Append a tensor vector to tensor matrix

Viewed 2582

I have a tensor matrix that i simply want to append a tensor vector as another column to it.

For example:

    X = torch.randint(100, (100,5))
    x1 = torch.from_numpy(np.array(range(0, 100)))

I've tried torch.cat([x1, X) with various numbers for both axis and dim but it always says that the dimensions don't match.

3 Answers

You can also use torch.hstack to combine and unsqueeze for reshape x1

torch.hstack([X, x1.unsqueeze(1)])

Shape of X is [100, 5], while the shape of X1 is 100. For concatenation torch requires similar shape on all the axis apart from the one in which we are trying to concatenate.

so, you will first need to

X1 = X1[:, None] # change the shape from 100 to [100, 1]
Xc = torch.cat([X, X1], axis=-1) /# tells the torch that we need to concatenate over the last dimension

Xc.shape should be [100, 6]

Combining the two answers into a pytorch 1.6 compatible version:

torch.cat((X, x1.unsqueeze(1)), dim = 1)

Related