mathjs icon indicating copy to clipboard operation
mathjs copied to clipboard

Improve the docs for sparse matrices

Open cshaa opened this issue 4 years ago • 5 comments

It is almost impossible to learn how to use SparseMatrix from the current documentation. The example code also isn't very useful. We need to improve the documentation and make it easier to grasp and include some real-world examples.

(Possibly related to #1166 and #1770?)

cshaa avatar Mar 12 '20 20:03 cshaa

Yeah, the documentation on the possibilities and limitations of SparseMatrix are a bit... sparse ;)

Anyone interested in writing a bit more about SparseMatrices? Maybe the https://mathjs.org/docs/datatypes/matrices.html page is the best place, not sure.

josdejong avatar Mar 14 '20 13:03 josdejong

Could you provide a URL to the sparse code?

hsmyers avatar Apr 04 '20 22:04 hsmyers

@hsmyers there is not one place with the sparse code. You can find the code of the SparseMatrix class here: https://github.com/josdejong/mathjs/blob/develop/src/type/matrix/SparseMatrix.js. Besides that, all functions have a implementations for multiple data types, amongs others SparseMatrix, for example see add.js. Is that what you mean?

josdejong avatar Apr 05 '20 08:04 josdejong

@josdejong Exactly what I meant. Mostly the first link so I could go over which 'sparse' you were using. I assumed that add.js was how you were handling the multiple variants for each function needed. Let me poke around a bit and give it some thought.

hsmyers avatar Apr 05 '20 16:04 hsmyers

May be it might help someone to know the internals of a SparseMatrix:

Lets consider a matrix generated using the following code:

A = math.sparse([[1,0,0],[4,0,0],[7,0,9]]);

Note that A has a fully populated first column, and no elements in the second column, and a single element in the third column. This code results in an object A which has the following fields:

A._values array with the all the non-zero values [1,4,7,9].

A._index contains the row indices for each element in A._values i.e. [0,1,2,2]. This implies that the value 1 is in row 0, value 4 is in row 1, and the value 7 is in row 2 of column 1.

A._ptr is an array that contains the starting and ending indices for each column in the values array. The starting index of the column colNo in the values array is stored in A._ptr[colNo] and the ending index in A._ptr[colNo+1]. For this example, A._ptr would be [0,3,3,4]. This means that the first column starts at index 0 and ends at index 3, hence A._values[0] to A._values[3] will contain the first column. The second column starts at index 3 and ends at 3 meaning it has no elements. Likewise, the third column starts at index 3, and ends at index 4.

A._size contains the size of the matrix which in this case is [3,3].

A.type returns "SparseMatrix"

VivekTRamamoorthy avatar Oct 04 '22 16:10 VivekTRamamoorthy