# Generalized Inverse in Snap!

Months ago I went down a rabbit hole after saying I could deliver on a generalized inverse algorithm. It's possible, but would be painfully slow using standard techniques (and I can't think of any other stable methods.) I got as far as QR decomposition on small test matrices before giving up. The underlying problem is the list of lists representation of a matrix in Snap!, which requires tearing apart and reassembling a matrix over and over again. Standard techniques go to great length to operate on matrices in place to minimize memory usage as well as time. The JS math/matrix libraries use flat lists for their implementations.
It may be possible to have a reasonably quick implementation in pure Snap! with a flat representation of matrices as a single array/list with metadata for structure, and I almost went down this route, but then all the the surrounding matrix operations/functions would not apply. So, I gave up and this is my report.

Thank you!

If you operate on the matrix with commands (ADD, REPLACE, etc.) it will be stored as a JS dynamic array. Umm wait, no, it'll be a dynamic array of pointers to dynamic arrays. @jens, do we maybe want to change that? Have an ARRAY constructor that makes a single flat dynamic array? That's sort of what you've done for costumes, but generalized to user-constructed data. I bet that would speed up a lot of the APL library, too!

Well, if you know you're working on non-linked lists you could do all this in Snap!. You could use JS Function and list.contents to always work with the internal arrays. https://github.com/jmoenig/Snap/blob/master/src/lists.js#L119

I bet with JS function you could just augment List in a Snap! library. I do think this would be really useful for matrix operations. You could add a flag for "linearized" or something, and one for dimensions - and even just adapt the other setters and getters to work with that.

In-place updates though for other APL things would mean having a command-block-based library.

Oh yes, if we start down this road I'll have to rewrite the entire library, I know.

It's certainly doable in Snap!, although it would be faster with better underlying JS support. Your notion of getting at list contents misses a bit of the point because the matrix rows aren't guaranteed to be contiguous, so simple indexing schemes won't work. But the original motivation was that Brian wanted the generalized inverse function to complete the APL stuff.
There are a few JS implementations of matrix math that could be implemented, but then you have a parallel implementation of matrix representation and operations. That's a lot of work and is a big conceptual break.