# Compute cartesian product for batched tensor

**URL:** <https://discuss.pytorch.org/t/compute-cartesian-product-for-batched-tensor/128121>\
**Category:** Uncategorized\
**Created:** [July 30, 2021, 7:43am UTC](https://discuss.pytorch.org/t/compute-cartesian-product-for-batched-tensor/128121 "2021-07-30T07:43:56Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Samue1](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/s/f04885/32.png) [@Samue1](https://discuss.pytorch.org/u/Samue1)\
**Post date:** [July 30, 2021, 7:43am UTC](https://discuss.pytorch.org/t/compute-cartesian-product-for-batched-tensor/128121/1 "2021-07-30T07:43:56Z")

</div>

I have the following tensor

```auto
x = torch.tensor([[[[4, 6],
                    [12, 10]],
                   [[20, 22],
                    [28, 30]]],
                  [[[1, 6],
                    [13, 15]],
                   [[16, 18],
                    [29, 26]]]])

```

with dimensions `(batch_size, channels, height, width)`. Now I want to apply `torch.cartesian_prod()` to each element of the batch. I can use `.flatten(start_dim=0)` to get a one-dimensional tensor for each batch element with shape `(batch_size, channels*height*width)`. However, `torch.cartesian_prod()` is only defined for one-dimensional tensors. Is there a workaround to compute the cartesian product for each batch dimension?

Currently I use

```auto
batch_size = 2
indices = list()
for batch in range(batch_size):
        indices.append(torch.cartesian_prod(x[batch], x[batch]))

```

which is not really elegant.
