稀疏矩阵乘法用c语言表示完整代码
时间: 2024-10-12 12:14:36 浏览: 60
稀疏矩阵乘法是一种优化的矩阵乘法算法,适用于矩阵中大部分元素为0的情况。下面是用C语言表示稀疏矩阵乘法的完整代码:
```
#include <stdio.h>
#define MAX_SIZE 100
typedef struct {
int row;
int col;
int val;
} Triple;
void sparse_matrix_multiply(Triple a[], Triple b[], Triple c[]) {
int m = a[0].row, n = b[0].col, t = 0;
int row_terms[MAX_SIZE], bstart[MAX_SIZE + 1];
int i, j, k, sum;
// 计算b中每行第一个非零元素的位置
for (i = 1; i <= n; i++) {
bstart[i] = 0;
}
for (i = 1; i <= b[0].val; i++) {
bstart[b[i].col]++;
}
for (i = 2; i <= n; i++) {
bstart[i] += bstart[i - 1];
}
// 计算a中每行第一个非零元素的位置
for (i = 1; i <= m; i++) {
row_terms[i] = 0;
}
for (i = 1; i <= a[0].val; i++) {
row_terms[a[i].row]++;
}
for (i = 2; i <= m; i++) {
row_terms[i] += row_terms[i - 1];
}
// 稀疏矩阵乘法
for (i = 1; i <= m; i++) {
for (j = 1; j <= n; j++) {
sum = 0;
for (k = row_terms[i]; k < row_terms[i + 1]; k++) {
while (bstart[a[k].col] <= bstart[a[k].col + 1]) {
if (b[bstart[a[k].col]].row == j) {
sum += a[k].val * b[bstart[a[k].col]].val;
break;
}
bstart[a[k].col]++;
}
}
if (sum != 0) {
t++;
c[t].row = i;
c[t].col = j;
c[t].val = sum;
}
}
}
// 存储结果
c[0].row = m;
c[0].col = n;
c[0].val = t;
}
int main() {
Triple a[] = {{3, 3, 3}, {1, 1, 1}, {1, 2, 2}, {2, 2, 3}, {3, 3, 4}};
Triple b[] = {{3, 3, 3}, {1, 2, 1}, {2, 1, 2}, {3, 3, 3}};
Triple c[MAX_SIZE];
int i;
sparse_matrix_multiply(a, b, c);
printf("Result:\n");
for (i = 1; i <= c[0].val; i++) {
printf("%d %d %d\n", c[i].row, c[i].col, c[i].val);
}
return 0;
}
```
阅读全文