function [coordinates,vaf,stress,numiter] = smacof(prox,numdim)

warning off MATLAB:divideByZero

n = size(prox,1);

D = prox;

stressone = sum(sum(D.^2))/2;

Z = unifrnd(-2,2,n,numdim);

DZ = squareform(pdist(Z));

stresstwo = sum(sum(DZ.^2))/2;

stressthree = sum(sum(D.*DZ));

oldstress = stressone + stresstwo - stressthree;

tol = 10^(-6);

dstress = realmax;

numiter = 1;

dstress = oldstress;

while ((dstress > tol) & (numiter <= 100000))
    
    numiter = numiter + 1;
    
    BZ = -D./DZ;
    
    for i = 1:n
        BZ(i,i) = 0;
        BZ(i,i) = -sum(BZ(:,i));
    end
    
    X = n^(-1)*BZ*Z;
    
    Z = X;
    
    DZ = squareform(pdist(Z));
    
    stresstwo = sum(sum(DZ.^2))/2;
    
    stressthree = sum(sum(D.*DZ));
    
    newstress = stressone + stresstwo - stressthree;
    
    dstress = oldstress - newstress;
    
    oldstress = newstress;
end

stress = newstress;

coordinates = Z;

distances = pdist(coordinates);

proximities = squareform(prox);

corrmatrix = corrcoef(distances',proximities');

vaf = corrmatrix(1,2)^2;

