Working script, but it still iterates over all the rows. It might be possible to do it working on the whole matrises at once, and then much faster.