This is a quick post on how to convert multiple matrices into a single vector using Python’s *numpy* package. To begin with let us define 2 matrices.

1 2 3 4 5 |
import numpy as np mat1 = np.array([[1,2,3,4,5,6] , [7,8,9,10,11,12]]) mat2 = np.array([[20,21,22,23,24,25] , [26,27,28,29,30,31]]) |

What we want to do is to merge the contents of *mat1* and *mat2* into a single vector. To reach that goal first we need to convert each of them into vectors. For this we will make use of Numpy’s *reshape.*

1 2 3 |
mat1_single = np.reshape(mat1, -1) mat2_single = np.reshape(mat2, -1) |

The *-1 *value for the *newshape* parameter of *reshape* ensures that the output has only 1 dimension. A matrix with 1 dimension is called a vector, which is what we want to achieve. Now that we have *flattened *both the matrices, we can merge (concatenate) them into a single vector using

1 |
mat = np.concatenate((mat1_single, mat2_single)) |

So the final script and it’s output look like this

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import numpy as np mat1 = np.array([[1,2,3,4,5,6] , [7,8,9,10,11,12]]) mat2 = np.array([[20,21,22,23,24,25] , [26,27,28,29,30,31]]) import numpy as np mat1 = np.array([[1,2,3,4,5,6] , [7,8,9,10,11,12]]) mat2 = np.array([[20,21,22,23,24,25] , [26,27,28,29,30,31]]) mat1_single = np.reshape(mat1, -1) mat2_single = np.reshape(mat2, -1) mat = np.concatenate((mat1_single, mat2_single)) print(mat) print(mat.shape) |

## Leave A Comment