# Extract (ultrametric) distances from hclust or dendrogram

How can the matrix of (ultrametric) distances be extracted from the result of hclust (or a dendrogram in general) in R?

The distance of two units in a dendrogram is defined as the smallest distance at which the two units (or the clusters which they are part of) merge.

For example, in the attached dendrogram, the (ultrametric) distance between unit 1 and 4 is 2.36.

These are often known as cophenetic distances and can be extracted using the cophenetic() function. This function works with hclust() objects, any object with a as.hclust() method (so hierarchical cluster methods in the cluster package) and object of class "dendrogram".