Learn R Programming

plotlsirm (version 0.1.3)

crossdist_fast: Fast pairwise (cross) Euclidean distances

Description

Computes the Euclidean distance between every row of a "person" matrix (z, shape \(N \times d\)) and every row of an "item" matrix (w, shape \(I \times d\)). An optional item_labels argument lets you collapse items into groups first, replacing each group with its centroid before distances are calculated.

Usage

crossdist_fast(z, w, item_labels = NULL)

Value

A numeric distance matrix.

  • When item_labels is NULL, the result is \(N \times I\): distance from every person to every item.

  • When item_labels is provided, the result is \(N \times G\), where \(G\) is the number of distinct groups.

Arguments

z

Numeric matrix of shape \(N \times d\). Each row is a point in a d-dimensional latent space representing a person.

w

Numeric matrix of shape \(I \times d\). Each row is a point in a d-dimensional latent space representing an item.

item_labels

Optional character or factor vector of length \(I\) giving a group label for each item row in w.

  • If supplied, the function first replaces the items in each group with their centroid (mean position) so the output contains distances to those centroids rather than to individual items.

  • If NULL (default), distances are computed to every item.

Details

The computation exploits the identity $$\|z_j-w_i\|^2 = \|z_j\|^2 + \|w_i\|^2 - 2\, z_j^\top w_i.$$ allowing all pairwise squared distances to be obtained with a single matrix multiplication. Negative rounding errors are clipped at zero before taking the square root.

Examples

Run this code
set.seed(42)
z <- matrix(rnorm(15), nrow = 5)   # 5 persons in 3-D
w <- matrix(rnorm(30), nrow = 10)  # 10 items in 3-D

# Person-item distances
d_full <- crossdist_fast(z, w)

# Person-group distances (items grouped into two sets)
grp <- rep(c("A", "B"), each = 5)
d_group <- crossdist_fast(z, w, item_labels = grp)

Run the code above in your browser using DataLab