DS Class 7-Sparse Matrix-AI&ML (1)
DS Class 7-Sparse Matrix-AI&ML (1)
elements.
Benefits of using the sparse matrix
• Array representation
• Linked list representation
2D array representation of
sparse matrix
• Row - It is the index of a row where a non-zero element
is located in the matrix.
• Column - It is the index of the column where a non-zero
element is located in the matrix.
• Value - It is the value of the non-zero element that is
located at the index (row, column).
The sparse
matrix -
the space occupied by the sparse matrix would be 8*8 = 64, whereas
the space occupied by the table represented using triplets would be 8*3
= 24.
#include <stdio.h>
int main()
{
// Sparse matrix having size 4*5
int sparse_matrix[4][5] =
{
{0 , 0 , 6 , 0 , 9 },
{0 , 0 , 4 , 6 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 1 , 2 , 0 , 0 }
};
// size of matrix
int size = 0;
for(int i=0; i<4; i++)
{
for(int j=0; j<5; j++)
{
if(sparse_matrix[i][j]!=0)
{
size++;
}
}
}
// Defining final matrix
int matrix[3][size];
int k=0;
// Computing final matrix
for(int i=0; i<4; i++)
{
for(int j=0; j<5; j++)
{
if(sparse_matrix[i][j]!=0)
{
matrix[0][k] = i;
matrix[1][k] = j;
matrix[2][k] = sparse_matrix[i][j];
k++;
}
}
}
// Displaying the final matrix
for(int i=0 ;i<3; i++)
{
for(int j=0; j<size; j++)
{
printf("%d ", matrix[i][j]);
printf("\t");
}
printf("\n");
}
return 0;
}
Linked List representation of the
sparse matrix
• The advantage of using a linked list to represent the
sparse matrix is that the complexity of inserting or
deleting a node in a linked list is lesser than the array.
• https://www.youtube.com/watch?v=VL03KD-RxZc
• https://www.youtube.com/watch?v=sr_bR1WwcLY
• https://www.youtube.com/watch?v=E6IOrZUpvSE