MATLAB: How to access cells of n-dimensional array without colon operator

colon n-dimensional n-dim ndim arrays matrixesevalMATLAB

I need to develop a function that can accept any n-dimensional arrays. It should access cells of the arrays in the following way:
mat(1:end-1, :, :, ... :);
mat( :, 1:end-1, :, ... :);
mat( :, :, 1:end-1, ... :);
mat( :, :, :, ... 1:end-1);
And also by other similar combinations for more then one dimension, e.g.:
mat(1:end-1, :, 1:end-1, ... :);
How can it be done in a smarter way, so I do not need to consider all cases manually, and it can be universal for any number of dimensions?
I was looking for something as:
new_mat = function(mat, (vector with dimensions to be used), (vectors used to access cells, e.g., 1:end-1));
For example it could be:
new_mat = function(mat, [1 3], [1:end-1; 2:end]);
which is equivalent to:
new_mat = mat(1:end-1, :, 1:end-1, ... :);
GREAT THANKS!

Best Answer

That was a fun post-lunch challenge, thanks!
extractFromND(magic(3),[1 2],[2 3;3 3])
It does not accept end you have to pass in the calculation yourself, e.g.
size(x,4)-1 %equivalen to end-1 in dim 4
The function
function Mextract = extractFromND(M,dim,datarange)
% EXTRACTFROMND extract data range in dim from M
%











%Usage:
% -Mextract = extractFromND(M,dim,datarange);
%
%Inputs:
% -M: nd matrix
% -dim: dimensions that the rows of datarange use
% -datarange: [dim x 2] where each row is the range in low/high in dim
%
%Outputs:
% -MExtract: M not including data outside of datarange in dim of M
%
%
%Examples:
%
% x = ones(3,3,3,3,3);
% x2 = extractFromND(x,[1 5],[2 3;1 2]);
% size(x2);
%
%See Also: colon
%
%
%TODO: make datarange nx3 with middle column the stride
%
%
% Copyright 2013 The MathWorks, Inc.
% SCd 735494
%
%Rudimentary error checking
assert(nargin==3,'Exactly three inputs expected');
ndM = ndims(M);
assert(max(dim)<=ndM,'Can''t pull from more dimensons than we have');
ned = numel(dim); %numel extract dimensions
assert(size(datarange,1)==ned,'datarange should have the same number of rows as dim');
szM = size(M);
assert(all(szM(dim).'>=datarange(:,2)),'out of range datarange');
%Engine:
%Build index vector
idx = repmat({':'},1,ndM);
for ii = 1:ned
idx{dim(ii)} = datarange(ii,1):datarange(ii,2);
end
%Extract from M:
Mextract = M(idx{:});
end