input: Write a Python class to perform various matrix operations like addition, subtraction, multiplication, and transpose. The class should initialize a matrix from a list of values and be able to perform these operations on other matrices of appropriate dimensions. Provide the implementation of the class and examples of method usage.
  assert str(Matrix(2, 2, [1, 2, 3, 4]))=="1 2 \n3 4 \n"
  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, [5, 6, 7, 8])))=="6 8 \n10 12 \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, values):
          self.rows = rows
          self.cols = cols
          self.values = values
  
      def __str__(self):
          return '\n'.join(' '.join(map(str, self.values[i*self.cols:(i+1)*self.cols])) for i in range(self.rows)) + '\n'
  
      def transpose(self):
          transposed_values = [self.values[i + j*self.rows] for j in range(self.cols) for i in range(self.rows)]
          return Matrix(self.cols, self.rows, transposed_values)
  
      def add(self, other):
          if self.rows != other.rows or self.cols != other.cols:
              raise ValueError("Matrices must have the same dimensions for addition")
          result_values = [self.values[i] + other.values[i] for i in range(len(self.values))]
          return Matrix(self.rows, self.cols, result_values)
  
      def sub(self, other):
          if self.rows != other.rows or self.cols != other.cols:
              raise ValueError("Matrices must have the same dimensions for subtraction")
          result_values = [self.values[i] - other.values[i] for i in range(len(self.values))]
          return Matrix(self.rows, self.cols, result_values)
  
      def mul(self, other):
          if self.cols != other.rows:
              raise ValueError("Number of columns in the first matrix must be equal to the number of rows in the second matrix")
          result_values = []
          for i in range(self.rows):
              for j in range(other.cols):
                  sum = 0
                  for k in range(self.cols):
                      sum += self.values[i*self.cols + k] * other.values[k*other.cols + j]
                  result_values.append(sum)
          return Matrix(self.rows, other.cols, result_values)