How to add two sparse matrices stored in 2d arrays??

Recommended Answers

All 5 Replies

No idea, you have not given any info of your code or problem.

Sorry...
Addition of two sparse matrix sp1 and sp2 and the result to be stored in matrix sp3

There is no type called sparse matrix in C.

you need to be more specific about the problem your having
is there a specific error in your code or do you need suggestions on how to get started

A sparse matrix has the following appearance:

spmatrix[0][0] = total number of rows in sparse matrix
spmatrix[0][1] = total number of columns in sparse matrix
spmatrix[0][2] = total number of non-zero values

index variable must be greater than zero

s[index][0] = row value of non-zero value
s[index][1] = column value of non-zero value
s[index][2] = actual non-zero value

The first thing you want to do is verify that the number of rows and number of columns for both sparse matrices that are to be added are equal. Both matrices must have the same number of rows and columns.

Next you have to set up a temp variable for total number of non-zero values for each sparse matrix. This will be used in a while loop to iterate thru all the values. Keep in mind that your interations will begin with ONE instead of ZERO since ZERO provides the configuration data of the sparse matrix as indicated above.

In the while loop, you will first compare spmatrix1 row with spmatrix2 row , if spmatrix1 row is less than smpmatrix2 row , it (spmatrix1) is copied to spmatrix3, the copy will include the row, column and value. If spmatrix1 row is greater than spmatrix2 row, then spmatrix2 is copied to spmatrix3 (again row,column and value is copied)

If an equal condition exists between spmatrix1 row and spmatrix2 row, you now have to make a comparison of spmatrix1 column and spmatrix2 column, and copy the lesser column to your new matrix.

Also, keep in mind that you have to increment the index of the source and target matrix every time you make a copy from the source to the target.

I realize that this might not be the best explanation of sparse matrix addition. It's been a long time since I was a student and this info is a recollection from my student days. But at least it's a starting point.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.