Sathvik Purushotham
Sathvik Purushotham

Reputation: 3

Transpose of sparse matrix in C

I've been trying to write a program that displays the sparse matrix and also finds the transpose of the matrix, but while transposing only the elements of the first row of the original matrix are getting transposed and all the other elements from other rows are getting ignored. I need some help.

Here's the code I've written

#include <stdio.h>
#include <stdlib.h>

struct Element{
    int i;
    int j;
    int x;
};

struct Sparse{
    int m;
    int n;
    int num;
    struct Element *ele;
};

void create(struct Sparse *s){
    printf("Enter the dimensions ");
    scanf("%d%d",&s->m, &s->n );
    printf("Number of non-zero elements");
    scanf("%d",&s->num);
    s-> ele= (struct Element*) malloc(s->num * sizeof(struct Element));
    printf("Enter all non-zero elements\n");
    for (int i = 0; i< s->num; i++)
    {
        scanf("%d%d%d",&s->ele[i].i,&s->ele[i].j,&s->ele[i].x);
    }
}
void display(struct Sparse s){
    int i,j,k=0;
    for (i = 0; i < s.m; i++)
    {
        for (j = 0; j < s.n; j++)
        {
            if(i==s.ele[k].i && j== s.ele[k].j)
                printf("%d ",s.ele[k++].x);
            else
                printf("0 ");
        }
        printf(" \n");
    }
}
void createTranspose(struct Sparse *t, struct Sparse s){
    t->m = s.n;
    t->n = s.m;
    t->num = s.num;
    t-> ele= (struct Element*) malloc(t->num * sizeof(struct Element));
    printf("Enter all non-zero elements\n");
    for (int i = 0; i< t->num; i++)
    {
        t->ele[i].i= s.ele[i].j;
        t->ele[i].j= s.ele[i].i;
        t->ele[i].x= s.ele[i].x;
    }
}

int main(){
    struct Sparse s, t;
    create(&s);
    display(s);
    createTranspose(&t,s);
    printf("Transpose of the matrix is \n");
    display(t);
    return 0;
}

Output

Enter the dimensions 6 6
Number of non-zero elements6
Enter all non-zero elements
0 0 1
0 2 2
0 4 3
2 3 4
4 1 5
5 5 6
1 0 2 0 3 0
0 0 0 0 0 0
0 0 0 4 0 0
0 0 0 0 0 0
0 5 0 0 0 0
0 0 0 0 0 6
Enter all non-zero elements
Transpose of the matrix is
1 0 0 0 0 0
0 0 0 0 0 0
2 0 0 0 0 0
0 0 0 0 0 0
3 0 0 0 0 0
0 0 0 0 0 0

Some help to get a proper output would be highly appreciated.

Upvotes: 0

Views: 5724

Answers (1)

Your display function assumes that the sparse elements are in row-major order, but after simple transpose they're now in column-major order.

Either you need to re-sort the sparse elements that they retain the row-major ordering, or you need an inner loop in your display routine:

    for (k = 0; k < s.num; k++) {
        if (i == s.ele[k].i && j == s.ele[k].j) {
             printf("%d ", s.ele[k].x);
             break;
        }
    }

    // not found among the sparse elements
    if (k == s.num) {
        printf("0 ");
    }

Upvotes: 1

Related Questions