# How to do matrix operations with this way of storing sparse matrices

I read the way of storing the five or seven point laplace matrix for some poisson problem but I don't understand how can i multiply, add and subtract this stored sparse matrix by a vector or another matrix?

The way says that we just store the diagonal entries which are the coefficients of the i,j,k unknown in adiag matrix and the coefficients of the i+,j,k neighbours will be stored in another array ax and for the j neighbours as well.

• Where did you read this? – nicoguaro Jul 11 '17 at 1:39
• In Robert bridson's book fluid simulation for computer graphics – Anas Alaa Jul 11 '17 at 10:12

## 1 Answer

Think about it this way: in your matrix, you know exactly where the entries are nonzero (and you store what these values are), and everything else is zero. If you just write down the usual matrix-vector product,

for (i=1...N)
for (j=1...N)
output[i] += matrix[i,j] * input[j];


then you realize that most of these additions just add zeros because the matrix entry is zero. You can avoid all of those unnecessary operations if you remember where your nonzero entries are, and then only do those products and additions that are necessary. This is in essence what the book is suggesting: have a way to know where the nonzero entries of the matrix are, store what their values are, and then shrink the loop above to only those operations that are necessary.

• So if the matrix has the non zeros at the diagonal so we store them in an array adiag(i, j, k) and for the coefficients of the neighbours of the cell (i, j, k) in the positive x we will use ax(i, j, k) and ay (i, j, k) how can we do the multiplication? – Anas Alaa Jul 12 '17 at 12:03
• @AnasAlaa -- you just repeat your original question. Have you thought about how my answer could get you closer to understanding how this may be done? – Wolfgang Bangerth Jul 19 '17 at 3:04