Here's a C implementation for multiplying a CSR (Compressed Sparse Row) matrix with a CSC (Compressed Sparse Column) matrix:
#include <stdio.h>
#include <stdlib.h>
// Structure to represent sparse matrix in CSR format
typedef struct {
int rows; // Number of rows
int cols; // Number of columns
int* row_ptr; // Row pointers
int* col_indices; // Column indices
double* values; // Non-zero values
int nnz; // Number of non-zero elements
} CSRMatrix;
// Structure to represent sparse matrix in CSC format
typedef struct {
int rows; // Number of rows
int cols; // Number of columns
int* col_ptr; // Column pointers
int* row_indices; // Row indices
double* values; // Non-zero values
int nnz; // Number of non-zero elements
} CSCMatrix;
// Function to multiply CSR and CSC matrices
double* multiply_csr_csc(CSRMatrix* A, CSCMatrix* B, int* result_rows, int* result_cols) {
// Check matrix compatibility
if (A->cols != B->rows) {
fprintf(stderr, "Matrix dimensions incompatible for multiplication\n");
return NULL;
}
// Allocate result matrix
*result_rows = A->rows;
*result_cols = B->cols;
double* result = calloc((*result_rows) * (*result_cols), sizeof(double));
if (!result) {
fprintf(stderr, "Memory allocation failed\n");
return NULL;
}
// Multiplication algorithm
for (int i = 0; i < A->rows; i++) {
// Iterate through rows of A
for (int j = A->row_ptr[i]; j < A->row_ptr[i+1]; j++) {
int k_A = A->col_indices[j];
double val_A = A->values[j];
// Find corresponding column in B
for (int k = B->col_ptr[k_A]; k < B->col_ptr[k_A+1]; k++) {
int col_B = B->row_indices[k];
double val_B = B->values[k];
// Multiply and accumulate
result[i * (*result_cols) + col_B] += val_A * val_B;
}
}
}
return result;
}
// Utility function to print matrix
void print_matrix(double* matrix, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%7.2f ", matrix[i * cols + j]);
}
printf("\n");
}
}
int main() {
// Example CSR Matrix
int csr_rows = 3;
int csr_cols = 3;
int csr_nnz = 6;
int row_ptr[] = {0, 2, 3, 6};
int col_indices[] = {0, 2, 1, 0, 1, 2};
double csr_values[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
CSRMatrix A = {
.rows = csr_rows,
.cols = csr_cols,
.row_ptr = row_ptr,
.col_indices = col_indices,
.values = csr_values,
.nnz = csr_nnz
};
// Example CSC Matrix (same data, different representation)
int csc_rows = 3;
int csc_cols = 3;
int csc_nnz = 6;
int col_ptr[] = {0, 2, 4, 6};
int row_indices[] = {0, 1, 0, 2, 1, 2};
double csc_values[] = {1.0, 4.0, 2.0, 5.0, 3.0, 6.0};
CSCMatrix B = {
.rows = csc_rows,
.cols = csc_cols,
.col_ptr = col_ptr,
.row_indices = row_indices,
.values = csc_values,
.nnz = csc_nnz
};
// Perform multiplication
int result_rows, result_cols;
double* result = multiply_csr_csc(&A, &B, &result_rows, &result_cols);
// Print result
if (result) {
printf("Result Matrix:\n");
print_matrix(result, result_rows, result_cols);
// Free allocated memory
free(result);
}
return 0;
}