input: Write a python function to create a Matrix class that supports initialization, addition, subtraction, multiplication, and transposition of matrices. 
  assert str(Matrix(2, 2, [1, 2, 3, 4]).transpose()) == '1 3 \n2 4 \n'
  assert str(Matrix(2, 2, [1, 2, 3, 4]).add(Matrix(2, 2, [1, 1, 1, 1]))) == '2 3 \n4 5 \n'
  assert str(Matrix(2, 2, [1, 2, 3, 4]).sub(Matrix(2, 2, [1, 1, 1, 1]))) == '0 1 \n2 3 \n'
  assert str(Matrix(2, 2, [1, 2, 3, 4]).mul(Matrix(2, 2, [1, 1, 1, 1]))) == '3 3 \n7 7 \n'
output: class Matrix:
      def __init__(self, rows, cols, elements):
          self.rows = rows
          self.cols = cols
          self.elements = elements
  
      def __str__(self):
          result = ''
          for i in range(self.rows):
              for j in range(self.cols):
                  result += str(self.elements[i * self.cols + j]) + ' '
              result = result.strip() + '\n'
          return result
  
      def transpose(self):
          transposed_elements = [0] * (self.rows * self.cols)
          for i in range(self.rows):
              for j in range(self.cols):
                  transposed_elements[j * self.rows + i] = self.elements[i * self.cols + j]
          return Matrix(self.cols, self.rows, transposed_elements)
  
      def add(self, other):
          if self.rows != other.rows or self.cols != other.cols:
              raise ValueError("Matrices must have the same dimensions for addition.")
          added_elements = [self.elements[i] + other.elements[i] for i in range(self.rows * self.cols)]
          return Matrix(self.rows, self.cols, added_elements)
  
      def sub(self, other):
          if self.rows != other.rows or self.cols != other.cols:
              raise ValueError("Matrices must have the same dimensions for subtraction.")
          subtracted_elements = [self.elements[i] - other.elements[i] for i in range(self.rows * self.cols)]
          return Matrix(self.rows, self.cols, subtracted_elements)
  
      def mul(self, other):
          if self.cols != other.rows:
              raise ValueError("Matrices are not aligned for multiplication.")
          result_elements = [0] * (self.rows * other.cols)
          for i in range(self.rows):
              for j in range(other.cols):
                  for k in range(self.cols):
                      result_elements[i * other.cols + j] += self.elements[i * self.cols + k] * other.elements[k * other.cols + j]
          return Matrix(self.rows, other.cols, result_elements)