wo80 / CSparse.NET

A concise library for solving sparse linear systems with direct methods.
GNU Lesser General Public License v2.1
58 stars 25 forks source link

Set value in SparseMatrix is unable? #40

Closed Thiago-NovaesB closed 1 year ago

Thiago-NovaesB commented 1 year ago

I can get the value using matrix.At(row, col), but I can't find a way to set the value.

wo80 commented 1 year ago

There is no such method. The reason is that setting a single value in a sparse matrix is very inefficient (involves a binary search and possibly memory reallocation).

The SparseMatrix class gives you public access to the ColumnPointers, RowIndices and Values arrays, so feel free to set the values directly, but usually there are better ways than accessing the values of a sparse matrix like that. Could you explain your use case?

Thiago-NovaesB commented 1 year ago

My problem is the following: I have to solve a sequence of sparse square linear systems. In each iteration, some coefficients will change. I have the row, column and new value for each coefficient that needs to change. I used Mathnet's dense matrices, but with CSparse it greatly reduced the resolution time, but I think I can improve the problem modification time. I tried: 1) Build the sparse matrix with Mathnet. In each iteration set the news values using Mathnet At operator, convert to CSparse and solve with CSparse. 2) Construct the dense matrix with double[,]. In each iteration set the news values using Array At operator, convert to CSparse using OfArray and solve with CSparse.

The above approaches are pretty similar with (1) slightly better in my tests.

Is there a better way to do this?

wo80 commented 1 year ago

In each iteration, some coefficients will change.

In what way do the values change exactly?

MathNet does provide the feature you are looking for in SparseCompressedRowMatrixStorage.cs, so you could either do the updates with MathNet and use the wiki example to compute the sparse factorization, or take the code and use it to create a similar method for CSparse.NET. I'll provide help, if necessary.

Thiago-NovaesB commented 1 year ago

Thanks for the explanations about sparse structures. Despite having a mask of coefficients, they are not necessarily non-zero. So I can't modify just the values without having to reallocate memory. I think the combination of Array[,]+CSparse will be enough for me. Thank you for your help.