Ad Code

C Program of sparse matrix.

 What is Sparse Matrix? 

A matrix is a two-dimensional data object made of m rows and n columns, therefore having total m x n values. If most of the elements of the matrix have 0 value, then it is called a sparse matrix.

Eg:           0 0 3 0 4

                 0 0 5 7 0

                 0 0 0 0 0

                 0 2 6 0 0

Why to use Sparse Matrix instead of simple matrix ?


  • Storage: There are lesser non-zero elements than zeros and thus lesser memory can be used to store only those elements.
  • Computing time: Computing time can be saved by logically designing a data structure traversing only non-zero elements..

Representation of Spars Matrix in 2D Array


Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes in the matrix are of no use in most of the cases. So, instead of storing zeroes with non-zero elements, we only store non-zero elements. This means storing non-zero elements with

  • triples- (Row, Column, value).
2D array is used to represent a sparse matrix in which there are three rows named as

Row: Index of row, where non-zero element is located

Column: Index of column, where non-zero element is located

Value: Value of the non zero element located at index – (row, column)


Below, Representation it in triples( row, column, value)

           0 0 3 0 4                            row 1 1 2 2 4 4

           0 0 5 7 0                      column 3 5 3 4 2 3

           0 0 0 0 0                         value 3 4 5 7 2 6

           0 2 6 0 0


Let's understand with a program.


#include<stdio.h>
#include<conio.h>
void main()
{ int sparse[4][5]={0};
int i,j;
clrscr();
printf("Enter the sparse matrix:");
for(i=0;i<4;i++)
for(j=0;j<5;j++)
scanf("%d",&sparse[i][j]);
int size=0;
for(i=0;i<4;i++)
for(j=0;j<5;j++)
if(sparse[i][j]!=0)
size++;
int compact_matrix[3][15];
int k=0;
for(i=0;i<4;i++)
for(j=0;j<5;j++)
if(sparse[i][j]!=0)
{
compact_matrix[0][k]=i;
compact_matrix[1][k]=j;
compact_matrix[2][k]=sparse[i][j];
k++;
}
printf("The sparse matrix is as follows:");
for(i=0;i<3;i++)
for(j=0;j<size;j++)
printf("%d",compact_matrix[i][j]);
printf("\n");
getch();
}

Post a Comment

0 Comments

Ad Code