0

I have an array like so:

([[[ 0,  1,  2],
 [ 3,  4,  5]],

[[ 6,  7,  8],
[ 9, 10, 11]],

[[12, 13, 14],
[15, 16, 17]]])

If i want to slice the numbers 12 to 17 i would use:

arr[2, 0:2, 0:3]

but how would i go about slicing the array to get 12 to 16?

kmario23
  • 57,311
  • 13
  • 161
  • 150
Raphael Estrada
  • 1,109
  • 11
  • 18

2 Answers2

2

You'll need to "flatten" the last two dimensions first. Only then will you be able to extract the elements you want:

xf = x.view(x.size(0), -1)  # flatten the last dimensions
xf[2, 0:5]
Out[87]: tensor([12, 13, 14, 15, 16])
Shai
  • 111,146
  • 38
  • 238
  • 371
1

Another way would be to simply index into the tensor and slice what is needed as in:

# input tensor 
t = tensor([[[ 0,  1,  2],
             [ 3,  4,  5]],

           [[ 6,  7,  8],
            [ 9, 10, 11]],

           [[12, 13, 14],
            [15, 16, 17]]])

# slice the last `block`, then flatten it and 
# finally slice all elements but the last one
In [10]: t[-1].view(-1)[:-1]   
Out[10]: tensor([12, 13, 14, 15, 16])

Please note that since this is a basic slicing, it returns a view. Thus making any changes to the sliced part would affect the original tensor as well. For example:

# assign it to some variable name
In [11]: sliced = t[-1].view(-1)[:-1] 
In [12]: sliced      
Out[12]: tensor([12, 13, 14, 15, 16])

# modify one element
In [13]: sliced[-1] = 23   

In [14]: sliced  
Out[14]: tensor([12, 13, 14, 15, 23])

# now, the original tensor is also updated
In [15]: t  
Out[15]: 
tensor([[[ 0,  1,  2],
         [ 3,  4,  5]],

        [[ 6,  7,  8],
         [ 9, 10, 11]],

        [[12, 13, 14],
         [15, 23, 17]]])
kmario23
  • 57,311
  • 13
  • 161
  • 150