# Create a sparse matrix

I am writing a FE program which calculates the displacements under a uniform load. I want to store the stiffness matrix in sparse form(COO) without using an external library.Assume an upper-bound for the number of non zero elements per row is known. My problem is that I can't assemble the matrix in a sparse form and all the examples that I found they take as input the whole matrix and then make it sparse. In my case I want the spasrsity from the beggining ,is that possible?

• COO comprises 3 arrays: row, col, data. Build those arrays any way you see fit. You probably need to sort them by row and col after, or insert them in a sorted order. What have you tried? – Charlie S Nov 3 '20 at 13:09
• Have you seen: scicomp.stackexchange.com/questions/14134 ? – MPIchael Nov 4 '20 at 9:29

The sparsity is going to depend on your choice of basis functions and the way you mesh the geometry of the problem you pick. If the basis is trilinear quadrilaterals on the cube meshing a cube that's 15x15x10, that gives one structure, if the domain is L-shaped, that gives something else.

If you know all three aspects: element type, underlying domain, and the division of that domain into elements, you have some hope of forming the sparsity before assembly. And unless you're trying to slowly build your matrix as you mesh (with lots of dynamic allocation and lazy evaluation), you're likely to have to know all this beforehand anyway.

Start with a matrix that only stores those entries you have explicitly written something nonzero to. For example (not particularly efficient, but feasible), you could do

class SparseMatrix {
using std::pair<int,int> ij_coordinates;
std::map<ij_coordinates,double> entries;

...
};


Initially, there are no entries, but as you add ones, the map fills up.

I would recommend Chapter 8 in Sparse Matrix Technology, by Sergio Pissanetzky, 1984. He shows how the element-node connectivity array, once put into a sparse matrix format, can be used to generate the node-node connectivity. This connectivity is the sparse matrix indices for a finite element method. This connectivity can be used to initialize the sparse matrix storage that is filled in with element assembly.