function [mD2C,CPTS] = expanseFcn2dV02(ARRAY);
% EXPANSEF(M) ===  Function to calculate the expanse, or mean distance to 
% center, of a given 'M' of grouped points.  It will not work unless each
% points has a group number in the fourth column of the matrix.  Outputs are 
% (1) the expanse value, and (2) a matrix giving the coordinates of the 
% group centers.

% First, two matrices are initialized for later use.
ALLD2C = [];
CPTS = [];

% The group indices are pulled out of the parent matrix.
GNS = ARRAY(:,4);

% Now, each group in turn has it's rows pulled from the input matrix, put 
% into matrix G, it's center calculated, and distances to that center for 
% each point.
for i = 1:max(GNS)                      % Loops over all group numbers.
    G = [];                             % Initialize G matrix each time.
    
    for row = 1:size(ARRAY,1)           % Loop over all rows of the input array.
        
        % Now the group no. is checked; if it matches i (the group of 
        % interest this time through), that row is put into the G matrix.
        if ARRAY(row,4) == i            
            I = ARRAY(row,:);            
            G = [G; I];
        end
    end 
    
    % Now, the centerpoint of the group is determined, by taking the average
    % x-coord and the average y-coord among the group members.  The point 
    % is defined by these calculated coordinates and placed in CP.
    avgX = mean(G(:,2));
    avgY = mean(G(:,3));
    CP = [avgX avgY];
    
    
    D2C = [];                   % Initialize distance-to-center matrix.
    
    % For each point, the distance to the cp is calculated, and place in the 
    % D2C matrix. 
    for p = 1:size(G,1)
        d2c = dist2d(G(p,2),G(p,3),avgX,avgY);
        D2C = [D2C; d2c];
    end
    
    % Center points are built into matrix CPTS, distances to centers into 
    % ALLD2C.
    CPTS = [CPTS; CP];
    ALLD2C = [ALLD2C; D2C];
end

CPTS;
ALLD2C = [[1:size(ARRAY,1)]' ALLD2C];       % Values are numbered.

% The mean of all these distances is found.
mD2C = mean(ALLD2C(:,2));
