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

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <algorithm>

using std::vector;

// 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 full sparse matrix from compact triplet form
vector<vector<int>> buildSparseFromCompact(const vector<vector<int>>& compact) {
    const vector<int>& rowIdx = compact[0];
    const vector<int>& colIdx = compact[1];
    const vector<int>& values = compact[2];

    // Determine matrix dimensions automatically
    int rows = *max_element(rowIdx.begin(), rowIdx.end()) + 1;
    int cols = *max_element(colIdx.begin(), colIdx.end()) + 1;

    // Create full matrix initialized with zeros
    vector<vector<int>> sparse(rows, vector<int>(cols, 0));

    // Fill matrix
    for (int i = 0; i < rowIdx.size(); i++) {
        sparse[rowIdx[i]][colIdx[i]] = values[i];
    }

    return sparse;
}

// Print a matrix
void printMatrix(const vector<vector<int>>& mat, const std::string& title) {
    std::cout << title << "\n";
    for (const auto& row : mat) {
        for (int x : row) std::cout << x << " ";
        std::cout << "\n";
    }
    std::cout << "\n";
}

int main() {
    vector<vector<int>> compact = {
        {0, 0, 1, 1, 1, 3, 3, 3, 4},  // row indices
        {2, 4, 2, 3, 6, 1, 2, 5, 4},  // column indices
        {3, 8, 5, 7, 1, 2, 6, 4, 9}   // values
    };

    printMatrix(compact, "Compact matrix:");

    vector<vector<int>> sparse = buildSparseFromCompact(compact);

    printMatrix(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 2 days ago by avibootz

Related questions

...