function n = numelHelper( fullSizeVec, isTable, varargin )
%numelHelper - common helper for distributed and codistributed numel

% Copyright 2009-2020 The MathWorks, Inc.

totalNumel = prod( fullSizeVec );
if nargin <= 2
    n = totalNumel; 
else
    % Cell-array type indexing, work out how many elements are referenced.
    % Get here when indexing like D{1,3:7,:}
    
    % First of all, use "size" to work out the size in the same dimensionality
    % as requested by varargin. We need to multiply together the trailing
    % elements of fullSizeVec so that it's the same length as varargin:
    requestedDimensionality = length( varargin );
    sizeInRequestedDimensionality = [fullSizeVec(1:requestedDimensionality-1) , ...
                        prod( fullSizeVec( requestedDimensionality:end ) )];
    
    % Special error messages for tables
    if isTable && requestedDimensionality == 1
        error(message('MATLAB:table:LinearSubscript'));
    elseif isTable && requestedDimensionality ~= 2 
        error(message('MATLAB:table:NDSubscript'));
    end
    
    % Calculate the result by multiplying together the number of elements in
    % each dimension. NB that we don't care here whether or not the
    % arguments specified exceed the size of the object.
    result = 1;
    for ii=1:length( varargin )
        arg = varargin{ii};
        
        if parallel.internal.indexing.isColonLiteral( arg )
            nthis = sizeInRequestedDimensionality(ii);
        elseif isnumeric( arg )
            nthis = numel( arg );
        elseif ischar( arg )
            % Apparently it is legal to index using other characters too.
            % For most arrays, each char is an index. For tables treat as
            % one scalar.
            if isTable
                nthis = 1;
            else
                nthis = numel( arg );
            end
        elseif islogical( arg )
            % Only count the true indices, so use find to locate them.
            nthis = numel(find(arg));
        
        elseif isTable && iscell( arg )
            % Only tables allow cell arrays as subscripts
            nthis = numel( arg );
            
        else
            error(message('parallel:distributed:NumelBadIndexType', class( arg )));
        end
        
        result = result * nthis;
    end
    n = result;
end

end
