【问题标题】:Transpose of sparse matrix in CC中稀疏矩阵的转置
【发布时间】:2020-09-20 16:59:21
【问题描述】:

我一直在尝试编写一个程序来显示稀疏矩阵并找到矩阵的转置,但是在转置时,只有原始矩阵第一行的元素被转置,所有其他元素都来自其他行被忽略。我需要一些帮助。

这是我写的代码

#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;
}

输出

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

我们将非常感谢您对获得正确输出的帮助。

【问题讨论】:

  • 这个bug在你的显示函数中。

标签: c matrix sparse-matrix


【解决方案1】:

您的显示函数假定稀疏元素按row-major 顺序排列,但经过简单转置后,它们现在按列优先顺序排列。

您需要重新排序保持行优先顺序的稀疏元素,或者您需要在显示例程中使用内部循环:

    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 ");
    }

【讨论】:

    猜你喜欢
    • 2023-04-10
    • 2021-11-25
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    • 2013-06-26
    相关资源
    最近更新 更多