C语言代码稀疏矩阵转置
时间: 2023-11-29 15:46:16 浏览: 94
以下是C语言代码稀疏矩阵转置的例子:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_TERMS 101
#define MAX_COL 101
typedef struct {
int row;
int col;
int value;
} term;
void transpose(term a[], term b[]) {
int n, i, j, currentb;
n = a[0].value;
b[0].row = a[0].col;
b[0].col = a[0].row;
b[0].value = n;
if (n > 0) {
currentb = 1;
for (i = 0; i < a[0].col; i++) {
for (j = 1; j <= n; j++) {
if (a[j].col == i) {
b[currentb].row = a[j].col;
b[currentb].col = a[j].row;
b[currentb].value = a[j].value;
currentb++;
}
}
}
}
}
int main() {
term a[MAX_TERMS], b[MAX_TERMS];
int i, j, k = 1, m, n;
printf("Enter the number of rows and columns: ");
scanf("%d %d", &m, &n);
printf("Enter the elements of matrix:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
int x;
scanf("%d", &x);
if (x != 0) {
a[k].row = i;
a[k].col = j;
a[k].value = x;
k++;
}
}
}
a[0].row = m;
a[0].col = n;
a[0].value = k - 1;
printf("Sparse matrix:\n");
for (i = 0; i < k; i++) {
printf("%d %d %d\n", a[i].row, a[i].col, a[i].value);
}
transpose(a, b);
printf("Transposed sparse matrix:\n");
for (i = 0; i < k; i++) {
printf("%d %d %d\n", b[i].row, b[i].col, b[i].value);
}
return 0;
}
```
阅读全文