function X = f_unfold_k(X, k)
% f_unfold_k  Mode-k unfolding of a K-way tensor into a matrix
%
%   Rearranges the tensor into a matrix where:
%     - Rows correspond to the k-th mode
%     - Columns correspond to all other modes flattened in order
%
%   Input:
%       X - Input K-way tensor of size sz = [d1, d2, ..., dK]
%       k - Mode to unfold (1-based index)
%
%   Output:
%       X - Matrix of size [sz(k), prod(sz(other modes))]

sz = size(X);       % Size of original tensor
K = length(sz);     % Number of modes (dimensions)

% Define row mode (R) and column modes (C)
R = k;                         % Mode to be unfolded as rows
C = [k+1:K, 1:k-1];            % Remaining modes in circular order

% Permute tensor so that mode-k becomes the first dimension
X = permute(X, [R, C]);

% Reshape into matrix: rows = sz(k), columns = product of other dimensions
X = reshape(X, [sz(R), prod(sz(C))]);
end
