2013-11-24 88 views
13

Python新手,在numpy中掙扎,希望有人能幫助我,謝謝!Python如何在numpy中結合兩個矩陣

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 

結果:

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

問題:如何使用A和B生成C,像MATLAB C=[A;B]

回答

22

使用numpy.concatenate

>>> import numpy as np 
>>> np.concatenate((A, B)) 
matrix([[ 1., 2.], 
     [ 3., 4.], 
     [ 5., 6.]]) 
8

您可以使用numpy.vstack

>>> np.vstack((A,B)) 
matrix([[ 1., 2.], 
     [ 3., 4.], 
     [ 5., 6.]]) 
1

如果你想在現有的列C的工作,你可以做到這一點就地:

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