def sq_to_dist(i, j, n):
    """Convert coordinate of square distance matrix to condensed matrix index.

    The condensed version of a squareform, pairwise distance matrix is
    a linearisation of the upper triangular, non-diagonal coordinates
    of the squareform distance matrix. This function returns the [i, j]-th
    coordinate of the condensed array.

    eg. given a squareform matrix,

    array([[  0.        ,  10.        ,  22.36067977],
           [ 10.        ,   0.        ,  14.14213562],
           [ 22.36067977,  14.14213562,   0.        ]])

    The condensed version of this matrix is:

    array([ 10.        ,  22.36067977,  14.14213562])

    Parameters
    ----------
    i : int
        i-th coordinate.
    j : int
        j-th coordinate.
    n : int
        Dimension n of n*n distance matrix.

    Returns
    -------
    index : int
        Position of pairwise distance [i, j] in
        condensed distance matrix.

    Reference
    ---------

    In the scipy.spatial.squareform documentation, it is shown that the
    index in the condensed array is given by
    {n choose 2} - {(n - i) choose 2} + (j - i - 1).
    Some simple arithmetic shows that this can be expanded to the formula below.
    The documentation can be found in the following link:

    http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.spatial.distance.squareform.html


    Examples
    --------
    >>> sq_to_dist(0, 1, 4)
    0
    >>> sq_to_dist(0, 3, 4)
    2
    >>> sq_to_dist(1, 2, 4)
    3

    """
    if i > j:
        i, j = j, i
    index = i * n + j - i * (i + 1) / 2 - i - 1
    return int(index)