Assigning value from single dimension to multidimension array

I have two tensor “a” and “b” with size [1,5,256,256] and [5] respectively. Let’s say b=[0 1 2 3 4].

I want to assign b[0] to a[0,0,:,:] , b[1] to a[0,1,:,:] etc. I tried to assign as below code but it shows the error " RuntimeError: The expanded size of the tensor (256) must match the existing size (5) at non-singleton dimension 2. Target sizes: [5, 256, 256]. Tensor sizes: [5]"

a=torch.zeros(1,5,256,256)
b=torch.linspace(0,4,5)
a[0,:,:,:]=b

Hi,

You just need to change the view of b to match in dimensions:

a[0,:,:,:]=b.view(-1, 1, 1)

It’s about Broadcasting semantics — PyTorch 1.7.0 documentation which has some criteria.

Bests

Thanks. It solve my issue.