function[T,B,W,within,between,total]=ssquares(data,solution);

%data is the n x p data matrix
%solution is the partition of the data

%T is the Total Sums-of-Squares Cross-Products Matrix
%B is the Between " "   "   "
%W is the Witihin " "   "   "
%total,within,and between are the traces of their respective matrices

[n,p]=size(data);

groups = max(solution);
nvec = zeros(1,groups);
grandmean = mean(data);
meanmat = repmat(grandmean,n,1);
diff = data - meanmat;
dev = diff';
T = dev*dev';

for j=1:groups
    nvec(j) = sum(solution==j);
end



%finding within matrix
tempdat=[];
corrarray=zeros(p,p,groups);
for j=1:groups
    [a,b]=size(data(solution==j,:));
    if a > 0    
    tempdat=[data(solution==j,:)];
    corrarray(:,:,j)=cov(tempdat);
    tempdat=[];
    end
end

sampsizearray=[];
for i=1:groups
    sampsizearray(:,:,i)=repmat(nvec(i),p,p);
end
mult = sampsizearray - ones(p,p,groups);
withintile = corrarray.*mult;

W = sum(withintile,3);

B = T - W;

within = trace(W);
between = trace(B);
total = trace(T);


