function X_cell = conv2cell(X, dim)
% [X_cell] = conv2cell(X, dim)
%    Converts a matrix into a cell array over a given dimension, while
%    conveying all the other dimensions to the level of the individual cell.
%
%    X           The matrix to be converted, and can be of any dimensionality.
%
%    dim         The dimension over which to convert into the cell array.
%                Default = 1.
%
%    X_cell      The resulting cell-array.

%    Created by Pim Mostert - may 30th, 2016

if (nargin < 2)
    dim = 1;
end

dims = size(X);
dimOut = dims(dim);

tmp = 1:length(dims);
tmp(dim) = [];

subDims = dims(tmp);
if (length(subDims) == 1)
    subDims = [subDims, 1];
end

X = permute(X, [dim, tmp]);
X = reshape(X, dimOut, []);

X_cell = cell(dimOut, 1);
for in = 1:dimOut
    X_cell{in} = reshape(X(in, :), subDims);
end

end
    