DChaps
DChaps

Reputation: 526

Append a tensor vector to tensor matrix

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.

Upvotes: 2

Views: 6929

Answers (3)

DChaps
DChaps

Reputation: 526

Combining the two answers into a pytorch 1.6 compatible version:

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

Upvotes: 0

Karan Dhingra
Karan Dhingra

Reputation: 133

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]

Upvotes: 1

Dishin H Goyani
Dishin H Goyani

Reputation: 7693

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

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

Upvotes: 6

Related Questions