A matrix is just a table of numbers (rows × columns).
A sparse matrix is a matrix where most of the elements are 0.
Instead of storing all elements (including 0s), we store only the non-zero elements with their row, column, and value.
[
At(Row,column) Value
At (0,2) → compact[0][0]=0, compact[1][0]=2, compact[2][0]=3]
#include <stdio.h>
int main() {
int rows = 4, cols = 4;
// Original sparse matrix
int sparse[4][4] = {
{0, 0, 3, 0},
{0, 0, 0, 0},
{0, 4, 0, 5},
{7, 0, 0, 0}
};
// Count non-zero elements
int size = 0; //size is used to count how many non-zero elements
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
if (sparse[i][j] != 0)
size++;
[ //Value at(Row,Col)
3 at (0,2) value = 3 → not zero → size = 1
4 at (2,1) value = 4 → not zero → size = 2
5 at (2,3) value = 5 → not zero → size = 3
7 at (3,0) value = 7 → not zero → size = 4 ]
// Compact matrix (3 × size)
int compact[3][size];// 3-> row,column,value
int k = 0; // k keeps track of which column we are filling in the compact matrix
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (sparse[i][j] != 0) {
compact[0][k] = i; // store Row index
compact[1][k] = j; // store Column index
compact[2][k] = sparse[i][j]; // store Value
k++; //k++ → move to next column
}
}
}
[
At(Row,column) Value
At (0,2) → compact[0][0]=0, compact[1][0]=2, compact[2][0]=3]
// Print compact matrix
printf("Row Col Value");
for (int i = 0; i < size; i++)
{
printf("%d %d %d\n", compact[0][i], compact[1][i], compact[2][i]);
}
return 0;
}