Search code examples
python-3.xnumpymatrixkeyword-argument

How to create a function that concatenates a variable number of matrices?


I would like to create a python function to concatenate several matrix this is the example for two matrix:

def create_matrix(number,rows,columns):
    matrix=np.full((rows,columns),number)
    return matrix

matrix1=create_matrix(0,1,2)
matrix2=create_matrix(1,1,3)
matrix3=create_matrix(2,1,4)

def concatenate_matrix(matrix1,matrix2):
    vector_pacient=np.hstack((matrix1,matrix2))
    return vector_pacient

print(concatenate_matrix(matrix1,matrix2))
print('result',concatenate_matrix(matrix1,matrix2).shape) 

This works very well for two matrices I got:

[[0 0 1 1 1]]
result shape (1, 5)

as I wanted, now I want to concatenate a variable number of matrices, I tried:

def concatenate_matrix2(*args):
    for arg in args:
        print(arg.shape)
        vector_pacient=np.hstack(arg)
    return vector_pacient
print(concatenate_matrix2(matrix1,matrix2,matrix3))
print(concatenate_matrix2(matrix1,matrix2,matrix3).shape)

however I got:

(1, 2)
(1, 3)
(1, 4)
[2 2 2 2]
(1, 2)
(1, 3)
(1, 4)
result shape (4,)

I don't understad where is the error, it should have a shape of:

(1,9)

and a matrix as follows:

[[0 0 1 1 1 2 2 2 2]]

So I would like to appreciate suggestions to fix my code.


Solution

  • There is an error with your for loop. It seems you want to do the following:

    def concatenate_matrix2(*args):
        vector_pacient = args[0]
        for i in range(1, len(args)):
            vector_pacient = np.hstack((vector_pacient, args[i]))
        return vector_pacient
    

    or more succinctly:

    def concatenate_matrix2(*args):
        return np.hstack(args)
    

    or also:

    def concatenate_matrix2(*args):
        return np.concatenate(args, axis=1)
    

    (... which work only if the dimensions of all matrices except for the concatenation axis match exactly - it works here since the dimensions 0 have the same size 1)