用c语言写出稀疏矩阵的乘法
时间: 2023-05-11 10:01:58 浏览: 75
稀疏矩阵乘法的C语言实现如下:
```c
#include <stdio.h>
#include <stdlib.h>
#define max(a, b) ((a) > (b) ? (a) : (b))
typedef struct {
int row, col, val;
} Triple;
void print_matrix(int **matrix, int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
void print_triple(Triple *triple, int len) {
for (int i = 0; i < len; i++) {
printf("(%d, %d, %d) ", triple[i].row, triple[i].col, triple[i].val);
}
printf("\n");
}
void sparse_matrix_multiply(Triple *a, int a_len, Triple *b, int b_len, int **c, int *c_row, int *c_col) {
if (a[0].col != b[0].row) {
printf("Error: incompatible matrix dimensions\n");
return;
}
int *row_index = (int *) malloc((a[0].row + 1) * sizeof(int));
for (int i = 0; i <= a[0].row; i++) {
row_index[i] = -1;
}
for (int i = 0; i < a_len; i++) {
if (row_index[a[i].row] == -1) {
row_index[a[i].row] = i;
}
}
*c_row = a[0].row;
*c_col = b[0].col;
*c = (int *) calloc((*c_row) * (*c_col), sizeof(int));
for (int i = 0; i < a[0].row; i++) {
if (row_index[i] == -1) {
continue;
}
for (int k = 0; k < b[0].col; k++) {
int sum = 0;
for (int j = row_index[i]; j < a_len && a[j].row == i; j++) {
int col = a[j].col;
int val = a[j].val;
for (int l = 0; l < b_len && b[l].row == col; l++) {
if (b[l].col == k) {
sum += val * b[l].val;
break;
}
}
}
(*c)[i * (*c_col) + k] = sum;
}
}
free(row_index);
}
int main() {
int a_row = 3, a_col = 4, a_len = 5;
Triple a[] = {
{3, 0, 1},
{0, 1, 2},
{1, 2, 3},
{2, 1, 4},
{2, 3, 5}
};
printf("Matrix A:\n");
int **matrix_a = (int **) calloc(a_row, sizeof(int *));
for (int i = 0; i < a_row; i++) {
matrix_a[i] = (int *) calloc(a_col, sizeof(int));
}
for (int i = 0; i < a_len; i++) {
matrix_a[a[i].row][a[i].col] = a[i].val;
}
print_matrix(matrix_a, a_row, a_col);
int b_row = 4, b_col = 2, b_len = 4;
Triple b[] = {
{0, 1, 2},
{1, 0, 3},
{2, 0, 4},
{2, 1, 5}
};
printf("Matrix B:\n");
int **matrix_b = (int **) calloc(b_row, sizeof(int *));
for (int i = 0; i < b_row; i++) {
matrix_b[i] = (int *) calloc(b_col, sizeof(int));
}
for (int i = 0; i < b_len; i++) {
matrix_b[b[i].row][b[i].col] = b[i].val;
}
print_matrix(matrix_b, b_row, b_col);
int *c, c_row, c_col;
sparse_matrix_multiply(a, a_len, b, b_len, &c, &c_row, &c_col);
printf("Matrix C:\n");
int **matrix_c = (int **) calloc(c_row, sizeof(int *));
for (int i = 0; i < c_row; i++) {
matrix_c[i] = (int *) calloc(c_col, sizeof(int));
}
for (int i = 0; i < c_row; i++) {
for (int j = 0; j < c_col; j++) {
matrix_c[i][j] = c[i * c_col + j];
}
}
print_matrix(matrix_c, c_row, c_col);
free(c);
for (int i = 0; i < a_row; i++) {
free(matrix_a[i]);
}
free(matrix_a);
for (int i = 0; i < b_row; i++) {
free(matrix_b[i]);
}
free(matrix_b);
for (int i = 0; i < c_row; i++) {
free(matrix_c[i]);
}
free(matrix_c);
return 0;
}
```
该程序实现了稀疏矩阵乘法,输入两个稀疏矩阵A和B,输出它们的乘积C。稀疏矩阵用三元组表示,其中每个元素包含行号、列号和值。程序首先将稀疏矩阵转换为普通矩阵,然后进行矩阵乘法,并将结果转换回稀疏矩阵形式。