Explain an efficient method of storing a sparse matrix in memory. Write a module to find the transpose of the sparse matrix stored in this way.
A matrix which contains number of zero entries in much higher number than the number of non zero entries is called sparse matrix. The normal method of representing matrices in memory as two-dimensional arrays may not be appropriate for sparse matrices. One may save space by storing only nonzero entries in the matrix. For example the matrix A (3*3 matrix) represented below
0 2 0
5 0 0
0 6 9
can be written in the sparse matrix form as follows:
3 3 4
0 1 2
1 0 5
2 2 6
2 3 9
Where the first row represent the dimension of matrix and last column tells us the number of nonzero values; second row onwards it is giving the position and value of the non zero number.
A function which is used to find transpose of a sparse matrix is:
void transpose(x,r,y)
int x[3][3],y[3][3],r;
{
int i,j,k,m,n,t,p,q,col;
m=x[0][0];
n=x[0][1];
t=x[0][2]; y[0][0]=n; y[0][1]=m; y[0][2]=t;
if(t>0)
q=1;
for (col=0;col<=n;col++)
for(p=1;p<=t;p++)
if(x[p][1]==col)
y[q][0]=x[p][1]; y[q][1]=x[p][0]; y[q][2]=x[p][2];
q++;
}
return;