Refactored matrixToCSV  into a single function