function index = end(M,position,numindices)
%END  Overloaded END for input/output models.
%
%   END(M,POSITION,NUMINDICES) returns the index corresponding to the last 
%   entry along the dimension POSITION in the input/output models or model 
%   array M.  NUMINDICES is the number of indices used in the indexing 
%   expression.
%
%   For example,
%      M(end,1) extracts the submodel from the first input to the last output
%      M(2,1,end) extracts the mapping from first input to second output in the 
%      last model of the model array M.
%
%   You can use the command
%      M(:,:,end+1) = RHS,
%   to grow an array M of input/output models.

%   Author(s): S. Almy, P. Gahinet
%   Copyright 1986-2010 The MathWorks, Inc.
sizes = size(M);
if position==numindices && numindices<length(sizes)
   % END is in the last position and there are fewer
   % indices than dimensions
   if position<3
      index = prod(sizes(position:2));   % collapse i/o dims
   else
      index = prod(sizes(position:end)); % collapse array dims
   end
else
   sizes = [sizes 1]; % '1' allows trailing singleton dims
   index = sizes(min(position,end));
end
