def diag_length(h, w, diagonal=0):
    """
    Returns the number of elements on the specified diagonal of a matrix with dimensions (h, w).

    :param h: int, height of the matrix
    :param w: int, width of the matrix
    :param diagonal: int, diagonal index of the matrix
    :return: a positive integer, zero if diagonal fall completely outside the matrix
    """
    if diagonal >= 0:
        return max(min(h, w - diagonal), 0)
    else:
        return max(min(w, h + diagonal), 0)