function [EXPANSE,CPTS] = expanseFcn2d(ARRAY,S);
% EXPANSEF2(ARRAY,S) ===  Function to calculate the expanse, or root-mean-squared  
% distance to center, of a given ARRAY of grouped points.  Outputs are   
% (1) the expanse value, and (2) a matrix giving the coordinates of the 
% group centers.  The second input, S, is the structure output of 'findgroups2d', 
% which is how it differs from 'expansef(M)'.  I.e., groups are not defined in 
% the points configuration file.


% First, three matrices are initialized for later use.
ALLSD2C = [];
CPTS = [];
EXPANSE = [];

% The group data are stored in a structure <S>.  The data are pulled out one group
% at a time to be dealt with.
for i = 1:size(S,2)                         % Loop over each group. 
    GRP = S(i).members;             % Pulls out the indices into the ARRAY for the
    %  group.
    
    % The full set of data for the group is now pulled from the ARRAY, and stored in
    % a matrix <G>.  
    G = [];                         
    for j = 1:size(GRP,2)           % For each element of GRP (ie each index to ARRAY)
        row_ind = GRP(1,j);         % The index...
        row = ARRAY(row_ind,:);     % ... is converted to a row from ARRAY.
        G = [G; row];               % and stored in G.
    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];
    
    
    SD2C = [];                   % Initialize distance-to-center matrix.
    
    % For each point, the squared distance to the cp is calculated, and place in the 
    % D2C matrix. 
    for p = 1:size(G,1)
        sd2c = (G(p,2)-avgX)^2 + (G(p,3)-avgY)^2;
        SD2C = [SD2C; sd2c];
    end
    
    % Center points are built into matrix CPTS, distances to centers into 
    % ALLD2C.
    CPTS = [CPTS; CP];
    ALLSD2C = [ALLSD2C; SD2C];
    
    % The mean of all these distances is found.
    MSD2C = mean(ALLSD2C);
    
    % And the 'expanse' is the sqrt of this mean. 
    grp_expanse = sqrt(MSD2C);
    
    EXPANSE = [EXPANSE; grp_expanse];
    ALLSD2C = [];
end

