Here you will get C program to find transpose of a sparse matrix.

Transpose of a matrix is obtained by interchanging rows and columns. In another way, we can say that element in the i, j position gets put in the j, i position. Transpose of the matrix B1 is obtained as B2 by inserting (i,j)th element of B1 as (j,i)th element in B2.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
#include<stdio.h> #define MAX 20 void printsparse(int[][3]); void readsparse(int[][3]); void transpose(int[][3],int[][3]); int main() { int b1[MAX][3],b2[MAX][3],m,n; printf("Enter the size of matrix (rows,columns):"); scanf("%d%d",&m,&n); b1[0][0]=m; b1[0][1]=n; readsparse(b1); transpose(b1,b2); printsparse(b2); } void readsparse(int b[MAX][3]) { int i,t; printf("\nEnter no. of non-zero elements:"); scanf("%d",&t); b[0][2]=t; for(i=1;i<=t;i++) { printf("\nEnter the next triple(row,column,value):"); scanf("%d%d%d",&b[i][0],&b[i][1],&b[i][2]); } } void printsparse(int b[MAX][3]) { int i,n; n=b[0][2]; //no of 3-triples printf("\nAfter Transpose:\n"); printf("\nrow\t\tcolumn\t\tvalue\n"); for(i=0;i<=n;i++) printf("%d\t\t%d\t\t%d\n",b[i][0],b[i][1],b[i][2]); } void transpose(int b1[][3],int b2[][3]) { int i,j,k,n; b2[0][0]=b1[0][1]; b2[0][1]=b1[0][0]; b2[0][2]=b1[0][2]; k=1; n=b1[0][2]; for(i=0;i<b1[0][1];i++) for(j=1;j<=n;j++) //if a column number of current triple==i then insert the current triple in b2 if(i==b1[j][1]) { b2[k][0]=i; b2[k][1]=b1[j][0]; b2[k][2]=b1[j][2]; k++; } } |

**Output**

*Enter the size of matrix (rows,columns):3 4*

*Enter no. of non-zero elements:4*

*Enter the next triple(row,column,value):1 0 5*

*Enter the next triple(row,column,value):1 2 3*

*Enter the next triple(row,column,value):2 1 1*

*Enter the next triple(row,column,value):2 3 2*

*After Transpose:*

*row column value*

*4 3 4*

*0 1 5*

*1 2 1*

*2 1 3*

*3 2 2*

Simplified CodingThanks a lot.. The simplest code I seen yet. cheers (Y)

vineetOk

Jayant IsswaniThanks for the code 🙂

JayuIt’s very simple and easy to understand code from all the sources available so far with me

hasanplZ post for multiplication of sparse

ninogood one.and good to learn

Sankalp Arorathat was good, really need it.

pallaviI want the algorithm for this code, it’s an assignment :(, can u pls post or reply me??

Amit Gamotthanks a lot but code has a very small mistake ……..in last 2nd for loop

its like :

the corrected one:

for(i=0;i<=b1[0][1];i++)

Valluri Narasimhasir,can you say the asymptotic complexity for this code

SANATH CHANDRANplease explain why you write if (i==b[j][1])?