How to reconstruct a full sparse matrix from a compact (triplet) matrix in Rust

1 Answer

0 votes
// A sparse matrix is a matrix in which the majority of elements are zero.

// To rebuild a sparse matrix from a compact (triplet) representation,
// We create a full matrix initialized with zeros, then place each
// non‑zero element at its (row, column) position.

// Build a full sparse matrix from compact triplet form
fn build_sparse_from_compact(compact: &[Vec<i32>], count: usize) -> Vec<Vec<i32>> {
    let row_idx = &compact[0];
    let col_idx = &compact[1];
    let values  = &compact[2];

    // Determine matrix dimensions automatically
    let mut max_row = 0;
    let mut max_col = 0;

    for i in 0..count {
        if row_idx[i] > max_row {
            max_row = row_idx[i];
        }
        if col_idx[i] > max_col {
            max_col = col_idx[i];
        }
    }

    let rows = (max_row + 1) as usize;
    let cols = (max_col + 1) as usize;

    // Create full matrix initialized with zeros
    let mut sparse = vec![vec![0; cols]; rows];

    // Fill matrix
    for i in 0..count {
        sparse[row_idx[i] as usize][col_idx[i] as usize] = values[i];
    }

    sparse
}

// Print a matrix
fn print_matrix(mat: &[Vec<i32>], title: &str) {
    println!("{}", title);
    for row in mat {
        for x in row {
            print!("{} ", x);
        }
        println!();
    }
    println!();
}

fn main() {
    // Compact matrix:
    // 0 0 1 1 1 3 3 3 4
    // 2 4 2 3 6 1 2 5 4
    // 3 8 5 7 1 2 6 4 9

    let compact = vec![
        vec![0, 0, 1, 1, 1, 3, 3, 3, 4], // row indices
        vec![2, 4, 2, 3, 6, 1, 2, 5, 4], // column indices
        vec![3, 8, 5, 7, 1, 2, 6, 4, 9], // values
    ];

    let count = 9;

    println!("Compact matrix:");
    for i in 0..3 {
        for j in 0..count {
            print!("{} ", compact[i][j]);
        }
        println!();
    }
    println!();

    let sparse = build_sparse_from_compact(&compact, count);

    print_matrix(&sparse, "Sparse matrix (auto-sized):");
}


/*
run:

Compact matrix:
0 0 1 1 1 3 3 3 4 
2 4 2 3 6 1 2 5 4 
3 8 5 7 1 2 6 4 9 

Sparse matrix (auto-sized):
0 0 3 0 8 0 0 
0 0 5 7 0 0 1 
0 0 0 0 0 0 0 
0 2 6 0 0 4 0 
0 0 0 0 9 0 0 

*/

 



answered 3 hours ago by avibootz

Related questions

...