def mult_diag(d, mat, left=True):
    """Efficient multiply a full matrix by a diagonal matrix.

    This function should always be faster than dot.

    Parameters
    ----------
    d : 1D np.ndarray (n)
        Contains the diagonal elements.
    mat : 2D np.ndarray (n,n)
        Contains the matrix

    Returns
    --------
    res (n, n)
        Result of multiplying the matrices

    Notes
    ------
    This code by:
    Pietro Berkes berkes@gatsby.ucl.ac...
    Mon Mar 26 11:55:47 CDT 2007
    http://mail.scipy.org/pipermail/numpy-discussion/2007-March/026807.html

    Examples
    --------
    >>> mat = np.random.randn(20,20)
    >>> d = np.random.randn(20)
    >>> assert np.allclose(mult_diag(d, mat, left=True), np.dot(np.diag(d), mat))
    >>> assert np.allclose(mult_diag(d, mat, left=False), np.dot(mat, np.diag(d)))
    """
    if left:
        return (d*mat.T).T
    else:
        return d*mat