josdejong / mathjs

An extensive math library for JavaScript and Node.js
https://mathjs.org
Apache License 2.0
14.43k stars 1.24k forks source link

Improve the docs for sparse matrices #1769

Open cshaa opened 4 years ago

cshaa commented 4 years ago

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?)

josdejong commented 4 years ago

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.

hsmyers commented 4 years ago

Could you provide a URL to the sparse code?

josdejong commented 4 years ago

@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?

hsmyers commented 4 years ago

@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.

VivekTRamamoorthy commented 2 years ago

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"