Concatenate arrays using numpy module

Asked

Viewed 2,354 times

3

One question, for the solution of linear systems: how to concatenate an array (matrix) A, an array (column vector) b, so that one has the "augmented" matrix of the system, A~ = [A b], using numpy?

2 answers

4


Suggested 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)

Exit 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.]]

2

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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.