# Higher Order Tensor of Variable Rank

I would like to write a function, that matricizes a higher order tensor according to the following rule:

Let $$\mathcal{A} \in \mathbb{C}^{I_{1} \times I_{2} \times \ldots \times I_{N}}$$ be a tensor of order $$N$$. The matrix unfolding $$\mathbf{A}_{(n)} \in \mathbb{C}^{I_{n} \times\left(I_{n+1} I_{n+2} \ldots I_{N} I_{1} I_{2} \ldots I_{n-1}\right)}$$ contains the element $$a_{i_{1} i_{2} \ldots i_{N}}$$ at the position with row number $$i_n$$ and column number equal to $$\begin{array}{l}{\left(i_{n+1}-1\right) I_{n+2} I_{n+3} \ldots I_{N} I_{1} I_{2} \ldots I_{n-1}+\left(i_{n+2}-1\right) I_{n+3} I_{n+4} \ldots I_{N} I_{1} I_{2} \ldots I_{n-1}+\cdots} \\ {\quad+\left(i_{N}-1\right) I_{1} I_{2} \ldots I_{n-1}+\left(i_{1}-1\right) I_{2} I_{3} \ldots I_{n-1}+\left(i_{2}-1\right) I_{3} I_{4} \ldots I_{n-1}+\cdots+i_{n-1}}\end{array}$$

How do a write a function, that will accept a higher order tensor of variable rank $$N$$ as an input?

Thanks

This should do what you want (you might want to double-check that):

unfold[ten_, n_] := Flatten /@ Transpose[ten, RotateRight[Range@TensorRank@ten, n - 1]]


This works by first rearranging the levels of the tensor from $$\{1,\dots,N\}$$ to $$\{n,n+1,\dots,N,1,\dots,n-1\}$$ and the flattening everything but the first level.

An example:

A = Array[Subscript[a, ##] &, {3, 3, 3}];

Column@Table[MatrixForm@unfold[A, n], {n, 3}]