Torch-2 Data manipulation

25 Dec 2015

Basic data manipulation in Torch

This section descibes basic manipulation with tensors in Torch.



t1 = torch.range(1,75)
t1 = t1:resize(3,5,5)

t2 = torch.range(1,25)
t2 = t2:resize(5,5)
print(t1)
print(t2)

--slice using [] operator
print(t1[1]) -- indices start from 1!

t1[1]:fill(2) -- fills the dimesion 1 elements with '2' in t1. 
print(t1)

-- using [{}] operator!

t2_slice1 = t2[{ {},2 }] -- returns  the elements of 2nd column
print(t2_slice1)


t2_slice2 = t2[{ 2,{} }] -- returns the elements of 2nd row
print(t2_slice2)

t2_slice3 = t2[{ {2},{}}] -- converts into a row matrix 1x5
print(t2_slice3)

t2_slice4 = t2[{ {1,5},{4,5}}] -- takes all elements from 1st to 5th row and 4th to 5th column
print(t2_slice4)

t2_slice5 = t2[{{2},{4}}] --  returns a tensor of element 2,4
print(t2_slice5)

t2_slice6 = t2[{2,4}]
print(t2_slice6)

t2_slice7 = t2[{{},{2,-2}}] -- starting from 2nd column till end-2 column
print(t2_slice7)

t2_slice8 = t2[{ -1,-1 }] -- prints element of end,end
print(t2_slice8)


t3 = torch.Tensor(5) -- copying subtensors
print(t3)
t3[{}] = t2[{{},1}]
print(t3)