Original to Sparse Matrix
In computer science and mathematics, a sparse matrix is a particular data structure that is used to store and operate matrices with a large number of zero or empty entries in an efficient manner. Sparse matrices minimize memory consumption by storing only the non-zero elements along with their row and column indices, in contrast to dense matrices, where the majority of the components are non-zero.
Sparse matrices are very useful in many applications (numerical simulations, machine learning, image processing, network analysis) where memory efficiency is critical.
They provide a number of benefits:
Diminished Memory Footprint: When compared to dense matrices, sparse matrices can significantly reduce memory usage by storing just non-zero elements and their locations. This is particularly crucial when working with sizable datasets.
Faster Operations: It is possible to optimize a number of sparse matrix operations, such as addition and multiplication, to work directly with the non-zero members. For some jobs, this can result in significant speed gains over dense matrices.
Enhanced Computational Efficiency: Sparse matrices’ lower memory requirements might result in faster and more effective numerical algorithms for solving linear systems of equations or conducting matrix factorization.
In summary, sparse matrices are a vital tool for optimizing memory usage and improving computational efficiency when dealing with matrices with a large number of zero values, making them a fundamental concept in various computational fields.
For Such more codes click here and for video tutorial click here.
/* Original Matrix to Sparse Matrix*/
#include
#include
void orgtosprs(int org[][20], int sparse[][3], int, int);
int main() {
int org[20][20], sparse[20][3];
int row, col, i, j;
printf("\n\nEnter the Row and Column of the original matrix : ");
scanf("%d %d", & row, & col);
printf("\n\nEnter the values for original matrix : ");
for (i = 0; i < row; i++)
for (j = 0; j < col; j++)
scanf("%d", & org[i][j]);
orgtosprs(org, sparse, row, col);
printf("\nAfter converting in Sparse Matrix : \n");
for (i = 0; i < sparse[0][2] + 1; i++) {
for (j = 0; j < 3; j++)
printf("%d\t", sparse[i][j]);
printf("\n");
}
}
void orgtosprs(int org[][20], int sparse[][3], int m, int n) {
int t = 1, i, j;
sparse[0][0] = m;
sparse[0][1] = n;
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
if (org[i][j] != 0) {
sparse[t][0] = i;
sparse[t][1] = j;
sparse[t][2] = org[i][j];
t++;
}
}
}
sparse[0][2] = t - 1;
}