Skip to main content

gram_matrix/
gram_matrix.rs

1//! Gram matrix: G = X · Xᵀ, used in kernel methods and feature covariance.
2//!
3//! Run: cargo run --example gram_matrix
4
5use matten::Tensor;
6
7fn main() {
8    // 4 data points × 3 features
9    let x = Tensor::new(
10        vec![1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0],
11        &[4, 3],
12    );
13
14    // G = X · Xᵀ: shape [4,4]
15    let g = x.matmul(&x.transpose());
16    println!("Gram matrix shape = {:?}", g.shape()); // [4,4]
17
18    // Diagonal: ||x_i||²
19    for i in 0..4 {
20        let diag = g.get(&[i, i]).unwrap();
21        println!("G[{i},{i}] = {diag:.1}");
22    }
23
24    // Symmetric check
25    for i in 0..4 {
26        for j in 0..4 {
27            assert!((g.get(&[i, j]).unwrap() - g.get(&[j, i]).unwrap()).abs() < 1e-10);
28        }
29    }
30    println!("Gram matrix is symmetric: OK");
31}