MATLAB: Indexing one particular dimension regardless of number of dimensions

indexing

I have a structure of several dimension (7 right now) that I will be adding dimensions to in the future. In a section of my code I need to isolate the third dimension into it's three components which right now I do like
outX = in(:,:,1,:,:,:,:); outY = in(:,:,2,:,:,:,:); outZ = in(:,:,3,:,:,:,:);
Is there a way to generalize this without having to edit the number of colons in the statement?
ex:
outX = coolFunction(in,3,1); outY = coolFunction(in,3,2); outZ = coolFunction(in,3,3);
Thanks!

Best Answer

function out = coolFunction(in, dim, page)
validateattributes(dim, {'numeric'}, {'scalar', 'positive', '<=', ndims(in)});
validateattributes(page, {'numeric'}, {'scalar', 'positive', '<=', size(in, dim)});
alldims = arrayfun(@(d) 1:d, size(in), 'UniformOutput', false);
alldims{dim} = page;
out = in(alldims{:});
end