refactor matrix operation