Checking Square Matrix | Linear Algebra using Python

Linear Algebra using Python | Checking Square Matrix: Here, we are going to learn how to check square matrix in Python?
Submitted by Anuj Singh, on May 21, 2020

Prerequisite: Linear Algebra | Defining a Matrix

Square Matrices are one of the important Matrices and therefore, we are going to write a python code to check whether the matrix is square or not?

Python code for checking square matrix

# Linear Algebra Learning Sequence
# Checking Square Matrix

import numpy as np

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

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

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

print("\n\n-----Matrix M---\n", M)

[r,c] = M.shape
if r == c:
    print("Matrix is square with dim ",r,'x',r )
else:
    print("Matrix is not square with dim ",r,'x',c )

V1 = np.array([[1,2,3],[2,3,5],[3,6,8],[323,623,823]])
V2 = np.array([[965,2413,78],[223,356,500],[312,66,78]])

[r2,c2] = V1.shape
[r3,c3] = V2.shape
print('\n\n----Matrix A----\n',V1)
if r2 == c2:
    print("Matrix is square with dim ",r2,'x',r2 )
else:
    print("Matrix is not square with dim ",r2,'x',c2 )

print('\n\n----Matrix B----\n',V2)
if r3 == c3:
    print("Matrix is square with dim ",r3,'x',r3 )
else:
    print("Matrix is not square with dim ",r3,'x',c3 )

Output:

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


-----Matrix M---
 [[45 78 65 99]
 [68 87 97 48]
 [74 68 77 48]]
Matrix is not square with dim  3 x 4


----Matrix A----
 [[  1   2   3]
 [  2   3   5]
 [  3   6   8]
 [323 623 823]]
Matrix is not square with dim  4 x 3


----Matrix B----
 [[ 965 2413   78]
 [ 223  356  500]
 [ 312   66   78]]
Matrix is square with dim  3 x 3



Comments and Discussions!

Load comments ↻






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