Multiplying a CSR (Compressed Sparse Row) matrix with a CSC (Compressed Sparse Column) matrix in C requires a bit more manual handling than in Python, as you don't have built-in data structures like in scipy.sparse.
Here’s a working and clear implementation in C for multiplying a CSR matrix with a CSC matrix.
✅ Assumptions:
- Matrix A: in CSR format
- Matrix B: in CSC format
- Result: stored in dense format (for simplicity)
✅ C Code
#include <stdio.h>
#include <stdlib.h>
// Helper to print dense matrix
void print_dense(double *mat, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++)
printf("%5.1f ", mat[i * cols + j]);
printf("\n");
}
}
// Multiply CSR (A) × CSC (B) -> Dense result
void multiply_csr_csc(
int A_rows, int A_cols,
const int *A_row_ptr, const int *A_col_idx, const double *A_vals,
int B_rows, int B_cols,
const int *B_col_ptr, const int *B_row_idx, const double *B_vals,
double *C // dense output matrix (A_rows x B_cols)
) {
for (int i = 0; i < A_rows; i++) {
for (int j = 0; j < B_cols; j++) {
double sum = 0.0;
// Loop over row i of A (CSR)
for (int ak = A_row_ptr[i]; ak < A_row_ptr[i + 1]; ak++) {
int a_col = A_col_idx[ak];
double a_val = A_vals[ak];
// Search for matching row in column j of B (CSC)
for (int bk = B_col_ptr[j]; bk < B_col_ptr[j + 1]; bk++) {
if (B_row_idx[bk] == a_col) {
double b_val = B_vals[bk];
sum += a_val * b_val;
break; // since there's a match
}
}
}
C[i * B_cols + j] = sum;
}
}
}
int main() {
// Example matrices: 3x3
// A (CSR)
// [1 0 2]
// [0 3 0]
// [4 0 0]
int A_rows = 3, A_cols = 3;
int A_row_ptr[] = {0, 2, 3, 4};
int A_col_idx[] = {0, 2, 1, 0};
double A_vals[] = {1.0, 2.0, 3.0, 4.0};
// B (CSC)
// [5 0 0]
// [0 0 8]
// [6 7 0]
int B_rows = 3, B_cols = 3;
int B_col_ptr[] = {0, 2, 3, 4};
int B_row_idx[] = {0, 2, 2, 1};
double B_vals[] = {5.0, 6.0, 7.0, 8.0};
// Result matrix C (dense)
double *C = calloc(A_rows * B_cols, sizeof(double));
multiply_csr_csc(A_rows, A_cols, A_row_ptr, A_col_idx, A_vals,
B_rows, B_cols, B_col_ptr, B_row_idx, B_vals,
C);
printf("Result Matrix C = A * B:\n");
print_dense(C, A_rows, B_cols);
free(C);
return 0;
}
✅ Explanation: