使用稀疏矩阵格式(如 CSR)将矩阵和向量相乘并不难,如果您为稀疏线性系统编写线性求解器库,这是一个基本且常见的操作。以Yousef Saad 的SPARSEKIT为例。在代码中,您会发现第一个子程序之一就是他所说的“amux”。您可以在下面查看它。可以看出,它相当简单。希望您能够在例如 MATLAB 中做同样的事情。
因此,当您处理稀疏矩阵时,您应该为此操作执行一个特殊的稀疏矩阵 - 向量积函数,并且可能他们在 MATLAB 中有它。他们是否能够重载“*”运算符 - 可能是,但我不确定是不是这样。
subroutine amux ( n, x, y, a, ja, ia )
!*****************************************************************************80
!
!! AMUX multiplies a CSR matrix A times a vector.
!
! Discussion:
!
! This routine multiplies a matrix by a vector using the dot product form.
! Matrix A is stored in compressed sparse row storage.
!
! Modified:
!
! 07 January 2004
!
! Author:
!
! Youcef Saad
!
! Parameters:
!
! Input, integer ( kind = 4 ) N, the row dimension of the matrix.
!
! Input, real X(*), and array of length equal to the column dimension
! of A.
!
! Input, real A(*), integer ( kind = 4 ) JA(*), IA(NROW+1), the matrix in CSR
! Compressed Sparse Row format.
!
! Output, real Y(N), the product A * X.
!
implicit none
integer ( kind = 4 ) n
real ( kind = 8 ) a(*)
integer ( kind = 4 ) i
integer ( kind = 4 ) ia(*)
integer ( kind = 4 ) ja(*)
integer ( kind = 4 ) k
real ( kind = 8 ) t
real ( kind = 8 ) x(*)
real ( kind = 8 ) y(n)
do i = 1, n
!
! Compute the inner product of row I with vector X.
!
t = 0.0D+00
do k = ia(i), ia(i+1)-1
t = t + a(k) * x(ja(k))
end do
y(i) = t
end do
return
end