Sparse Matrices
Ms. Divya Verma
Assistant Professor,IT
Definition
• A matrix can be defined as a two-
dimensional array having 'm' rows and 'n'
columns representing m*n matrix.
• There may be a situation in which a
matrix contains more number of ZERO
values than NON-ZERO values.Such a
matrix is known as Sparse Matrix.
• Sparse matrix is a matrix that contains
very few non-zero elements.
Sparsity of a sparse matrix is defined as the number of zero
valued elements divided by the total number of elements.
Here sparsity~64%
A matrix that is not sparse is called dense matrix.
Why do we need to use a sparse
matrix instead of a simple matrix?
• We can also use the simple matrix to store the elements in the
memory; then why do we need to use the sparse matrix. The
following are the advantages of using a sparse matrix:
Storage: As we know, a sparse matrix that contains lesser non-
zero elements than zero so less memory can be used to store
elements. It evaluates only the non-zero elements.
Computing time: In the case of searching n sparse matrix, we
need to traverse only the non-zero elements rather than
traversing all the sparse matrix elements. It saves computing
time by logically designing a data structure traversing non-zero
elements.
Representation of Sparse matrix
• For example, the following 4x4 matrix is a sparse Matrix.
• Conventional method of representation of such a matrix is not
space efficient.
• 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).
Sparse Matrix Representations can be done in many ways following
are two common representations:
Array representation
Linked list representation
Method 1: Using Arrays:
• 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)
Types of Sparse matrix
1) Diagonal Matrix
This is the square matrix where the non zero elements are
only where row = col ie at diagonal.
2) Tridiagonal Matrix
In this square matrix all elements other than those on
and on the diagonals immediately above and below this one are
zero.
Triangular Matrices
Tiangular Matrices is of 2 types:
a) Lower triangular b) Upper triangular
Program to check if given matrix is
sparse or not?
1. Size= rows*columns;
2. for(int i = 0; i < rows; i++){
3. for(int j = 0; j < cols; j++){
4. if(a[i][j] == 0)
5. count++;
6. }
7. }
8.
9. if(count > (size/2))
10. printf("Given matrix is a sparse matrix");
11. else
12. printf("Given matrix is not a sparse matrix");
13.
14.
Program to convert matrix
into triplex/sparse matrix