Python how to combine two matrices in numpy

Question:

new to Python, struggling in numpy, hope someone can help me, thank you!

from numpy  import *   
A = matrix('1.0 2.0; 3.0 4.0')    
B = matrix('5.0 6.0')
C = matrix('1.0 2.0; 3.0 4.0; 5.0 6.0')
print "A=",A
print "B=",B
print "C=",C

results:

A= [[ 1.  2.]
   [ 3.  4.]]
B= [[ 5.  6.]]
C= [[ 1.  2.]
   [ 3.  4.]
   [ 5.  6.]]

Question: how to use A and B to generate C, like in matlab C=[A;B]?

Asked By: ilovecp3

||

Answers:

Use numpy.concatenate:

>>> import numpy as np
>>> np.concatenate((A, B))
matrix([[ 1.,  2.],
        [ 3.,  4.],
        [ 5.,  6.]])
Answered By: Ashwini Chaudhary

You can use numpy.vstack:

>>> np.vstack((A,B))
matrix([[ 1.,  2.],
        [ 3.,  4.],
        [ 5.,  6.]])
Answered By: Roman Pekar

If You want to work on existing array C, you could do it inplace:

>>> from numpy  import *
>>> A = matrix('1.0 2.0; 3.0 4.0')
>>> B = matrix('5.0 6.0')

>>> shA=A.shape
>>> shA
(2L, 2L)
>>> shB=B.shape
>>> shB
(1L, 2L)

>>> C = zeros((shA[0]+shB[0],shA[1]))
>>> C
array([[ 0.,  0.],
       [ 0.,  0.],
       [ 0.,  0.]])

>>> C[:shA[0]]
array([[ 0.,  0.],
       [ 0.,  0.]])
>>> C[:shA[0]]=A
>>> C[shA[0]:shB[0]]=B
>>> C
array([[ 1.,  2.],
       [ 3.,  4.],
       [ 0.,  0.]])
>>> C[shA[0]:shB[0]+shA[0]]
array([[ 0.,  0.]])
>>> C[shA[0]:shB[0]+shA[0]]=B
>>> C
array([[ 1.,  2.],
       [ 3.,  4.],
       [ 5.,  6.]])
Answered By: yourstruly

For advanced combining (you can give it loop if you want to combine lots of matrices):

# Advanced combining
import numpy as np

# Data
A = np.matrix('1 2 3; 4 5 6')
B = np.matrix('7 8')
print('Original Matrices')
print(A)
print(B)

# Getting the size
shA=np.shape(A)
shB=np.shape(B)
rowTot=shA[0]+shB[0]
colTot=shA[1]+shB[1]
rowMax=np.max((shA[0],shB[0]))
colMax=np.max((shA[1],shB[1]))

# Allocate zeros to C
CVert=np.zeros((rowTot,colMax)).astype('int')
CHorz=np.zeros((rowMax,colTot)).astype('int')
CDiag=np.zeros((rowTot,colTot)).astype('int')

# Replace C
CVert[0:shA[0],0:shA[1]]=A
CVert[shA[0]:rowTot,0:shB[1]]=B
print('Vertical Combine')
print(CVert)

CHorz[0:shA[0],0:shA[1]]=A
CHorz[0:shB[0],shA[1]:colTot]=B
print('Horizontal Combine')
print(CHorz)

CDiag[0:shA[0],0:shA[1]]=A
CDiag[shA[0]:rowTot,shA[1]:colTot]=B
print('Diagonal Combine')
print(CDiag)

The result:

# Result
# Original Matrices
# [[1 2 3]
#  [4 5 6]]
# [[7 8]]
# Vertical Combine
# [[1 2 3]
#  [4 5 6]
#  [7 8 0]]
# Horizontal Combine
# [[1 2 3 7 8]
#  [4 5 6 0 0]]
# Diagonal Combine
# [[1 2 3 0 0]
#  [4 5 6 0 0]
#  [0 0 0 7 8]]

Credit: I edit yourstruly answer and implement what I already have on my code

Answered By: Py Foliage
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.