# How to tile a tensor?

**URL:** <https://discuss.pytorch.org/t/how-to-tile-a-tensor/13853>\
**Category:** Uncategorized\
**Created:** [February 20, 2018, 5:20pm UTC](https://discuss.pytorch.org/t/how-to-tile-a-tensor/13853 "2018-02-20T17:20:42Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![Edouard360](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/edouard360/32/5130_2.png) [@Edouard360](https://discuss.pytorch.org/u/Edouard360)\
**Post date:** [June 8, 2018, 10:13pm UTC](https://discuss.pytorch.org/t/how-to-tile-a-tensor/13853/4 "2018-06-08T22:13:39Z")

</div>

For a general solution working on any dimension, I implemented `tile` based on the `.repeat` method of torch’s tensors:

```auto
def tile(a, dim, n_tile):
    init_dim = a.size(dim)
    repeat_idx = [1] * a.dim()
    repeat_idx[dim] = n_tile
    a = a.repeat(*(repeat_idx))
    order_index = torch.LongTensor(np.concatenate([init_dim * np.arange(n_tile) + i for i in range(init_dim)]))
    return torch.index_select(a, dim, order_index)

```

**Examples:**

```auto
t = torch.FloatTensor([[1,2,3],[4,5,6]])
Out[54]: 
tensor([[1., 2., 3.],
        [4., 5., 6.]])

```

- Across dim 0:

```auto
tile(t,0,3)
Out[53]: 
tensor([[1., 2., 3.],
        [1., 2., 3.],
        [1., 2., 3.],
        [4., 5., 6.],
        [4., 5., 6.],
        [4., 5., 6.]])

```

- Across dim 1:

```auto
tile(t,1,2)
Out[55]: 
tensor([[1., 1., 2., 2., 3., 3.],
        [4., 4., 5., 5., 6., 6.]])

```

No benchmarking performed, though 🙂

---

_[View the full topic](https://discuss.pytorch.org/t/how-to-tile-a-tensor/13853)._
