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

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

// 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
int** buildSparseFromCompact(int compact[3][9], int count, int* outRows, int* outCols) {
    int* rowIdx = compact[0];
    int* colIdx = compact[1];
    int* values = compact[2];

    // Determine matrix dimensions automatically
    int maxRow = 0, maxCol = 0;
    for (int i = 0; i < count; i++) {
        if (rowIdx[i] > maxRow) maxRow = rowIdx[i];
        if (colIdx[i] > maxCol) maxCol = colIdx[i];
    }

    int rows = maxRow + 1;
    int cols = maxCol + 1;

    *outRows = rows;
    *outCols = cols;

    // Create full matrix initialized with zeros
    int** sparse = malloc(rows * sizeof(int*));
    for (int i = 0; i < rows; i++) {
        sparse[i] = calloc(cols, sizeof(int));
    }

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

    return sparse;
}

// Print a matrix
void printMatrix(int** mat, int rows, int cols, const char* title) {
    printf("%s\n", title);
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++)
            printf("%d ", mat[i][j]);
        printf("\n");
    }
    printf("\n");
}

int 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

    int compact[][9] = {
        {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
    };

    int count = 9;

    printf("Compact matrix:\n");
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < count; j++)
            printf("%d ", compact[i][j]);
        printf("\n");
    }
    printf("\n");

    int rows, cols;
    int** sparse = buildSparseFromCompact(compact, count, &rows, &cols);

    printMatrix(sparse, rows, cols, "Sparse matrix (auto-sized):");

    // Free memory
    for (int i = 0; i < rows; i++)
        free(sparse[i]);
    free(sparse);

    return 0;
}


/*
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 1 day ago by avibootz

Related questions

...