pythonpython-3.xpytorchtypeerrortensor

TypeError: only integer tensors of a single element can be converted to an index


n_inc = torch.tensor(1)
theta = torch.tensor(0.6109)
phi = torch.tensor(0)
k0 = torch.tensor(6.2832)    
    
kinc = k0*n_inc*[torch.sin(theta)*torch.cos(phi),
                 torch.sin(theta)*torch.sin(phi), 
                 torch.cos(theta)]
print(kinc)

When I am running the code, it is showing the following error message:

TypeError: only integer tensors of a single element can be converted to an index

Can anyone help me to resolve this?

Thanks to @Hamza for pointing out the mistake. The code is working using Numpy. Haven't found any direct way to do it with PyTorch.

import numpy as np
import torch

theta = 0.6109
phi = 0.0
k0 = 6.2832
n_inc = 1.0
    
kinc = k0*n_inc*np.array([np.sin(theta)*np.cos(phi), 
                          np.sin(theta)*np.sin(phi), 
                          np.cos(theta)])
kinc = torch.tensor(kinc)
print(kinc)

Solution

  • Assuming you know that when you multiply a list with a number, the list is duplicated with times equivalent to this number. This number should be integer, otherwise you will get the error you had:

    torch.tensor(0.6109)*[torch.sin(theta)*torch.cos(phi), #<--- it throws an error
                     torch.sin(theta)*torch.sin(phi), 
                     torch.cos(theta)]
    

    If you want to repeat the list, you only need to multiply the list with an integer tensor, not a float tensor.

    If you want to multiply the integer tensor by each element in the list. You should only convert the list to NumPy array:

    kinc = k0*n_inc*np.array([torch.sin(theta)*torch.cos(phi), #<- NumPy array not a list
                     torch.sin(theta)*torch.sin(phi), 
                     torch.cos(theta)])
    

    You do not need to convert the sin and cos to NumPy type.