You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
# include <stdio.h>
# include <stdlib.h>
# include <time.h>
typedef struct {
float * values ;
int * rowIndex ;
int * colIndex ;
int nonZeroCount ;
} SparseMatrix ;
void sparse_matmul ( SparseMatrix A , SparseMatrix B , SparseMatrix * C ) {
int rowsA = A . rowIndex [ A . nonZeroCount ] ;
int colsA = A . colIndex [ A . nonZeroCount ] ;
int rowsB = B . rowIndex [ B . nonZeroCount ] ;
int colsB = B . colIndex [ B . nonZeroCount ] ;
if ( colsA ! = rowsB ) {
printf ( " 维度不匹配,无法进行矩阵乘法。 \n " ) ;
return ;
}
C - > nonZeroCount = 0 ;
C - > values = ( float * ) malloc ( sizeof ( float ) * ( rowsA * colsB ) ) ;
C - > rowIndex = ( int * ) malloc ( sizeof ( int ) * ( rowsA * colsB ) ) ;
C - > colIndex = ( int * ) malloc ( sizeof ( int ) * ( rowsA * colsB ) ) ;
for ( int i = 0 ; i < A . nonZeroCount ; i + + ) {
for ( int j = 0 ; j < B . nonZeroCount ; j + + ) {
if ( A . colIndex [ i ] = = B . rowIndex [ j ] ) {
float val = A . values [ i ] * B . values [ j ] ;
int row = A . rowIndex [ i ] ;
int col = B . colIndex [ j ] ;
// 检查是否已经存在该元素
int exists = 0 ;
for ( int k = 0 ; k < C - > nonZeroCount ; k + + ) {
if ( C - > rowIndex [ k ] = = row & & C - > colIndex [ k ] = = col ) {
C - > values [ k ] + = val ;
exists = 1 ;
break ;
}
}
if ( ! exists ) {
C - > values [ C - > nonZeroCount ] = val ;
C - > rowIndex [ C - > nonZeroCount ] = row ;
C - > colIndex [ C - > nonZeroCount ] = col ;
C - > nonZeroCount + + ;
}
}
}
}
}
int main ( ) {
// 示例: 初始化两个稀疏矩阵A和B, 并调用sparse_matmul函数
// 注意:这里省略了稀疏矩阵的初始化代码,你需要根据实际情况来初始化
SparseMatrix A , B , C ;
// 初始化A和B...
clock_t start = clock ( ) ;
sparse_matmul ( A , B , & C ) ;
clock_t end = clock ( ) ;
printf ( " 稀疏矩阵乘法耗时: %lf 毫秒 \n " , 1000.0 * ( end - start ) / CLOCKS_PER_SEC ) ;
// 清理内存...
return 0 ;
}