Implementation method of constructing augmented matrix in Python

  • 2021-07-06 11:07:13
  • OfStack

Troublesome


# TODO  Construct an augmented matrix, assuming that A , b Same number of rows 
def augmentMatrix(A, b):
  if(len(A) != len(b)):
    raise 'The number of rows is different'
  result = []
  for i in range(len(A)):
    row = []
    for j in range(len(A[i])):
      row.append(A[i][j])
    for j in range(len(b[i])):
      row.append(b[i][j])
    result.append(row)    
  return result

After optimization


# TODO  Construct an augmented matrix, assuming that A , b Same number of rows 
def augmentMatrix(A, b):
  return [AA + bb for AA, bb in zip(A,b)]
 
A = [[1,2,3],[4,5,6],[7,8,9]]
b = [[1],[2],[3]]
print augmentMatrix(A,b)
[[1, 2, 3, 1], [4, 5, 6, 2], [7, 8, 9, 3]]

Note: Interpret AA+bb in 1. In python, expressions such as [1, 2, 3] + [4] return [1, 2, 3, 4]


Related articles: