Skip to main content

sparse_dot

Function sparse_dot 

Source
pub fn sparse_dot(
    a_indices: &[u32],
    a_values: &[f32],
    b_indices: &[u32],
    b_values: &[f32],
) -> f32
Available on crate feature sparse only.
Expand description

Sparse dot product for sorted index arrays.

Computes the inner product of two sparse vectors represented as (indices, values) pairs. Indices must be sorted in ascending order.

§Algorithm

Uses merge-join: two pointers advance through sorted indices, accumulating products when indices match. Time complexity O(|a| + |b|).

§Arguments

  • a_indices - Sorted indices for vector a
  • a_values - Values corresponding to a_indices
  • b_indices - Sorted indices for vector b
  • b_values - Values corresponding to b_indices

§Example

use innr::sparse_dot;

// Sparse vectors: a = [1.0 at index 0, 2.0 at index 2]
//                 b = [3.0 at index 0, 4.0 at index 3]
// dot(a, b) = 1.0 * 3.0 = 3.0 (only index 0 overlaps)
let a_idx = [0u32, 2];
let a_val = [1.0f32, 2.0];
let b_idx = [0u32, 3];
let b_val = [3.0f32, 4.0];

let result = sparse_dot(&a_idx, &a_val, &b_idx, &b_val);
assert!((result - 3.0).abs() < 1e-6);