1 function result = tunfold(A,d)
3 % TUNFOLD - tensor unfold - reduces the dimension of a tensor by "unfolding" along one direction
4 % (performs unfolding as described by deLathauwer in SIMAX 21(4):1253.)
6 % Example: given a 3D tensor, A,
12 % +----+ +----+ +----+
18 % unfold(A,1) = [ A(:,1,:) A(:,2,:) ... A(:,n2,:) ],
19 % unfold(A,2) = ( A(:,:,1)' A(:,:,2)' ... A(:,:,n3)' ),
20 % unfold(A,3) = ( A(1,:,:)' A(2,:,:)' ... A(n1,:,:)' )
22 % To fold the matrix back (i.e. undo the unfold), one *must* know the
23 % size of the final matrix and use the same permutation as the unfolding.
26 % A == permute( reshape( unfold(A,d) , sz([ d:-1:1 N:-1:(d+1) ]) ), ...
27 % [ d:-1:1 N:-1:(d+1) ] );
30 % Copyright 2008 W. Scott Hoge (wsh032580 at proton dot me)
32 % Licensed under the terms of the MIT License
33 % (https://opensource.org/licenses/MIT)
37 if (d > length(sz)), result = A; return; end;
39 result = reshape( permute( A, [ d:-1:1 N:-1:(d+1) ]), ...
40 [ sz(d) prod(sz([1:(d-1) (d+1):N])) ] );
42 % unfold(A,1) = reshape( permute( A, [ 1 3 2 ]), [sz(1) prod(sz(3:2)) ] )
43 % unfold(A,2) = reshape( permute( A, [ 2 1 3 ]), [sz(2) prod(sz([1 3])) ] )
44 % unfold(A,3) = reshape( permute( A, [ 3 2 1 ]), [sz(3) prod(sz([1 2])) ] )