在c中添加稀疏矩阵



如何正确添加每个稀疏矩阵?我有两个稀疏矩阵A和B,但是我写了关于add_matrix的代码,它不能正常工作

我认为printf("0");毁了一切那么我怎么写函数add_matrix呢?

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct element{
int row;
int col;
int value;
} element;
typedef struct SparseMatrix {
element* data;
int rows;
int cols;
int terms;
} SparseMatrix;

void matrix_transpose(SparseMatrix a, SparseMatrix *b) 
{
for (int r = 0; r < (a.terms); r++) {
b->data[r].row = a.data[r].col;
b->data[r].col = a.data[r].row;
b->data[r].value = a.data[r].value;
}
}
void add_matrix(SparseMatrix a, SparseMatrix b, SparseMatrix* c)
{
// this part
for (int i = 0; i < a.terms; i++) {
c->data[i].value = a.data[i].value + b.data[i].value;
}
}


void print_matrix(SparseMatrix a)
{
int n = a.rows;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
bool check = false;
for (int k = 0; k < a.terms; k++)
{
if (a.data[k].row == i && a.data[k].col == j)
{
printf("%2d", a.data[k].value);
check = true;
}
}
if (!check)
printf(" 0");
}
printf("n");
}
printf("n");
}
int main(void)
{
SparseMatrix A, B, C;
int n, num; //n*n matrix, num of values
scanf("%d %d", &n, &num);
A.cols = n;
A.rows = n;
A.terms = num;
A.data = (element*)malloc(sizeof(element) * num);
B.rows = n;
B.cols = n;
B.terms = num;
B.data = (element*)malloc(sizeof(element) * num);
C.rows = n;
C.cols = n;
C.data = (element*)malloc(sizeof(element) * num);  
C.terms = num;
for (int i = 0; i < num; i++)
{
scanf("%d %d %d", &A.data[i].row, &A.data[i].col, &A.data[i].value);
}
print_matrix(A);
matrix_transpose(A, &B);
print_matrix(B);
add_matrix(A, B, &C);
print_matrix(C);
free(A.data);
free(B.data);
free(C.data);
return 0;
}

输入3 0 0 0 3 1 2 5 2 0 7

期望输出值

6 0 70 0 57 5 0

我的代码输出

6 0 0 0 0 00 0 00 0 0

我调试过的

A和B的行,col不变

函数add_matrx没有考虑矩阵元素的实际位置:

void add_matrix(SparseMatrix a, SparseMatrix b, SparseMatrix* c)
{
for (int i = 0; i < a.terms; i++) {
//              ^^^^^^^^^^^
// Why are you assuming that both the matrices had the same
// amount of non-zero values? Are you sure that the resulting matrix
// will have exactly the same number of non-zeroes (in the same places)?
c->data[i].value = a.data[i].value + b.data[i].value;
// That may be right IF both a.data[i] and b.data[i] have the same
// row and column, otherwise you are summing the wrong elements.
// What are c->data[i].row and c->data[i].col now?
// Those are not initialized, leading to undefined behavior, e.g. I
// obtained this result running your program:
// 61014 0 0
// 0 0 0
// 0 0 0
}
}

我建议在从流中提取矩阵元素的值之后,在使用矩阵之前,按行和按列对矩阵元素进行排序,以使所有算法更容易(和更有效)。

相关内容

  • 没有找到相关文章