Creating a Matrix using Columns | Linear Algebra using Python

Linear Algebra using Python | Creating a Matrix using Columns: Here, we are going to learn how to create a matrix using columns in Python?
Submitted by Anuj Singh, on May 14, 2020

In the python code, we will build a matrix using columns. We can stack two arrays to form a matrix only and only if both the column vectors have the same dimensions. The following code shows how an inbuilt hstack() function can be used to stack three columns to form a matrix.

Python code for creating a matrix using columns

# Creating a Matrix using Columnsn

import numpy as np

#Use of np.array() to define columns
V1 = np.array([[45],[78],[65],[99]])
V2 = np.array([[68],[87],[97],[48]])
V3 = np.array([[74],[68],[77],[48]])


print("The column v1: ",V1)
print("The column v2: ",V2)
print("The column v3: ",V3)

#Making a Matrix using Vectors
M = np.hstack([V1,V2,V3])

print("\n\n -----Matrix M---\n", M)
print("\n\nShape of the matrix B: ", M.shape)

Output:

The column v1:  [[45]
 [78]
 [65]
 [99]]
The column v2:  [[68]
 [87]
 [97]
 [48]]
The column v3:  [[74]
 [68]
 [77]
 [48]]


 -----Matrix M---
 [[45 68 74]
 [78 87 68]
 [65 97 77]
 [99 48 48]]


Shape of the matrix B:  (4, 3)


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.