Refactor matrix finding code into seperate functions.