Concatenate arrays using numpy module

1
For the solution of linear systems: how to concatenate an array A, an array (vector column) b, so that we have the "augmented" matrix of the system, A ~ = [A b] , using numpy?

    
asked by anonymous 30.11.2016 / 02:38

1 answer

3

Suggestion of solution (the sample arrays A and b could be created more automatically, but so I thought the example would be more didactic):

import numpy as np

A = np.array([ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ])
b = np.array([17, 18, 19, 20])

# Cria uma nova matriz com 1 coluna a mais
Ab = np.zeros((A.shape[0], A.shape[1]+1))

# Copia a matriz original para a nova matriz
Ab[:,:-1] = A

# Copia o vetor, convertido em uma matriz de uma coluna, para a nova matriz
Ab[:,-1:] = b.reshape(A.shape[0], 1)

print('A:')
print(A)
print('')

print('b:')
print(b)
print('')

print('[A b]:')
print(Ab)

Output from this code:

A:
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]
 [13 14 15 16]]

b:
[17 18 19 20]

[A b]:
[[  1.   2.   3.   4.  17.]
 [  5.   6.   7.   8.  18.]
 [  9.  10.  11.  12.  19.]
 [ 13.  14.  15.  16.  20.]]
    
30.11.2016 / 03:21