Add tensor and array


This might be a special situation. I have a cuda tensor and a numpy array. What is the best way to add their elements one by one? For example:
tensor1 = [1,1,1,1,1]
array1 = [0,1,2,3,4]
result = tensor1 + array1 (not sure what function to use)
Desired results:
result = [1,2,3,4,5]

Thank you!


It depends if you want the result to be a numpy array or a Tensor? And in the second case, if you want the result to be on CPU or GPU?

Hi @albanD, thanks for reply. I want the result to be a GPU tensor. What could be the best way to do this?

This should do it:

result = tensor1 + torch.from_numpy(array1).to(tensor1.device)
1 Like