refactor and fix matrix