Add a constant variable to a cuda.FloatTensor
I have two question:


  1) I'd like to know how can I add/subtract a constante torch.FloatTensor of size 1 to all of the elemets of a torch.FloatTensor of size 30.
  
  2) How can I multiply each element of a torch.FloatTensor of size 30 by a random value (different or not for each).


My code:

import torch
dtype = torch.cuda.FloatTensor 
def main():
     pop, xmax, xmin   = 30, 5, -5
     x                 = (xmax-xmin)*torch.rand(pop).type(dtype)+xmin
     y                 = torch.pow(x, 2)
     [miny, indexmin]  = y.min(0)
     gxbest            = x[indexmin] 
     pxbest            = x
     pybest            = y
     v = torch.rand(pop)
     vnext = torch.rand()*v + torch.rand()*(pxbest - x) + torch.rand()*(gxbest - x)

main()


What is the best way to do it? I think I should so how convert the gxbest into a torch.FloatTensor of size 30 but how can I do that? 
I've try to create a vector:


  Variable(torch.from_numpy(np.ones(pop)))*gxbest 


But it did not work. The multiplication is not working also. 

RuntimeError: inconsistent tensor size

Thank you all for your help!


  1) How can I add/subtract a constant torch.FloatTensor of size 1 to all of the elements of a torch.FloatTensor of size 30?


You can do it directly in pytorch 0.2.

import torch

a = torch.randn(30)
b = torch.randn(1)
print(a-b)


In case if you get any error due to size mismatch, you can make a small change as follows.

print(a-b.expand(a.size(0))) # to make both a and b tensor of same shape



  2) How can I multiply each element of a torch.FloatTensor of size 30 by a random value (different or not for each)?


In pytorch 0.2, you can do it directly as well. 

import torch

a = torch.randn(30)
b = torch.randn(1)
print(a*b)


In case, if you get an error due to size mismatch, do as follows.

print(a*b.expand(a.size(0)))


So, in your case you can simply change the size of gxbest tensor from 1 to 30 as follows. 

gxbest = gxbest.expand(30)

