I can not change shape [4] to [4,1] using .view(4,1)?

I am very new to coding + pytorch

I have an input tensor torch.full((row,col), 2.0), called A
and I want to have an output looks like [[2,2,2], [4,4,4], [6,6,6], …], called B
The idea is to multiple A and B, pytorch will do broadcasting for me if I understand correctly.
So I tried:
r, c = A.size()
x = torch.arange( r ) + 1.0
the x has shape ‘torch.Size([4])’, it seems like not broadcastable, which means A*x reports error.

I tried a little experiment, y = torch.randn(4,1). Then A*y is ok. So I think this is because x has shape [4] and y has shape [4,1]. I tried to change x’s shape to [4,1] using x.view(4,1). But it didn’t work. The shape of x is still [4]. Could anyone help me on this? Thank you a lot for your time!

x.view(4, 1) doesn’t change x but returns a tensor (view) of shape 4 x 1 if you want you can assign it to a new variable and use that or plug it into your operation directly.

1 Like

The x vector should have c rows. Try this:

> >>> import torch
> >>> row=4; col=7
> >>> A=torch.full((row,col),2.0)
> >>> r,c=A.size()
> >>> r,c
> (4, 7)
> >>> x=torch.arange(c)+1.0
> >>> x
> tensor([1., 2., 3., 4., 5., 6., 7.])
> >>> A*x
> tensor([[ 2.,  4.,  6.,  8., 10., 12., 14.],
>         [ 2.,  4.,  6.,  8., 10., 12., 14.],
>         [ 2.,  4.,  6.,  8., 10., 12., 14.],
>         [ 2.,  4.,  6.,  8., 10., 12., 14.]])

Or, in a more simple way: In A*x, the number of rows for the x vector, should be equal to the number columns of matrix A.

1 Like

Thank you very much! It works exactly the way I want

Thank you very much!