The function computes matrix exponent and handles some special cases

def matrix_exponent(M):
    """
    The function computes matrix exponent and handles some special cases
    """

    if (M.shape[0] == 1): # 1*1 matrix
        Mexp = np.array( ((np.exp(M[0,0]) ,),) )

    else: # matrix is larger
        method = None
        try:
            Mexp = linalg.expm(M)
            method = 1
        except (Exception,) as e:
            Mexp = linalg.expm3(M)
            method = 2
        finally:
            if np.any(np.isnan(Mexp)):
                if method == 2:
                    raise ValueError("Matrix Exponent is not computed 1")
                else:
                    Mexp = linalg.expm3(M)
                    method = 2
                    if np.any(np.isnan(Mexp)):
                        raise ValueError("Matrix Exponent is not computed 2")

    return Mexp