Concatenate arrays using numpy module
A question, for the solution of linear systems: how to concatenate an array (array) A, an array (column vector) b, so that one has the "augmented" array of the system, A~ = [A b], using numpy?
3
Author: talesaraujo, 2016-11-30
2 answers
Solution suggestion (the example 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.]]
4
Author: Luiz Vieira, 2016-11-30 02:21:35
Another Way is:
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]])
out = np.concatenate((a,b.T), axis = 1)
2
Author: Joao Estrella, 2020-05-31 04:15:20