0% found this document useful (0 votes)
2 views

Transpose of a Matrix in Python with user input

The document provides Python code examples for various matrix operations including transposing, subtracting, rotating a matrix by 90 degrees, finding the inverse using NumPy, and calculating an electricity bill based on usage. Each section includes an algorithm and source code, demonstrating how to take user input and perform the respective operations. The document also outlines the conditions required for matrix inversion and the rates for electricity consumption.

Uploaded by

rincejohn80
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Transpose of a Matrix in Python with user input

The document provides Python code examples for various matrix operations including transposing, subtracting, rotating a matrix by 90 degrees, finding the inverse using NumPy, and calculating an electricity bill based on usage. Each section includes an algorithm and source code, demonstrating how to take user input and perform the respective operations. The document also outlines the conditions required for matrix inversion and the rates for electricity consumption.

Uploaded by

rincejohn80
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Transpose of a Matrix in Python with user input

What is the Transpose of a Matrix?


If a number of elements present in rows interchange with a number of elements
present in the column of the matrix then it is known as the Transpose of a matrix.

For Example:

Algorithm for Transpose of a Matrix


 Ask the user for the inputs of Rows & Columns of the matrix
 Create the matrix of m x n by using the input() function and nested list
comprehension. Here m = number of Rows and n = number of columns
 For storing the result create another matrix of n x m basically,the resultant
matrix is inverted of your original matrix and initially, it is Zero.
 Use nested for-loop and do transpose[j][i] = matrix[i][j]
 The last step is to print the transpose of a matrix.
Source code

row = int(input('Enter number of row: '))

col = int(input('Enter number of col: '))

matrix = [[int(input(f'column {j+1} -> ENter {i+1}


element:')) for j in range(col)] for i in range(row)]

transpose = [[0 for i in range(row)] for j in range(col)]

print() # for new line

print('matrix: ')

for i in matrix:

print(i)

for i in range(row):

for j in range(col):

transpose[j][i] = matrix[i][j]

print() # new line

print('Transpose of matrix: ')

for i in transpose:

print(i)

Output

Enter number of row: 3

Enter number of col: 3


column 1 -> ENter 1 element:1

column 2 -> ENter 1 element:2

column 3 -> ENter 1 element:3

column 1 -> ENter 2 element:4

column 2 -> ENter 2 element:5

column 3 -> ENter 2 element:6

column 1 -> ENter 3 element:7

column 2 -> ENter 3 element:8

column 3 -> ENter 3 element:9

matrix:

[1, 2, 3]

[4, 5, 6]

[7, 8, 9]

Transpose of matrix:

[1, 4, 7]

[2, 5, 8]

[3, 6, 9]
Subtraction of Two Matrix in python with User input

Rule for Subtraction of two matrix

You can subtract two matrices if the number of rows and number of columns is
the same for both the matrix.

Example:

Algorithm for Subtraction of two matrices

 Ask the user for the input of rows (m) & columns (n) of the matrix.
 Using input()function and list comprehension create matrix_A and
matrix_B of dimension m x n.
 For storing the result, create another matrix (result) of the same
dimension m x n and initially, it is Zero.
 Using nested for-loop do result[i][j] = matrix_A[i][j] - matrix_B[i][j] .
 At last print the resultant matrix(result).
Source Code

rows = int(input('ENter number of rows: '))

cols = int(input('ENter number of column: '))

print() # for new line

print('Enter values for matrix A')

matrix_A = [[int(input(f"column {j+1} -> ENter {i+1}


element:")) for j in range(cols)] for i in range(rows) ]

print() # for new line

print('Enter values for matrix B ')

matrix_B = [[int(input(f"column {j+1} -> ENter {i+1}


element:")) for j in range(cols)] for i in range(rows) ]

print() #for new line

print('Matrix-A :')

for i in matrix_A:

print(i)

print() #for new line

print('Matrix-B :')

for i in matrix_B:

print(i)

result = [[0 for j in range(cols)] for i in range(rows)]

for i in range(rows):

for j in range(cols):
result[i][j] = matrix_A[i][j] - matrix_B[i][j]

print() #for new line

print('Subtraction of Matrix-A and Matrix-B is :')

for i in result:

print(i)

Output:

ENter number of rows: 2

ENter number of column: 2

Enter values for matrix A

column 1 -> ENter 1 element:6

column 2 -> ENter 1 element:2

column 1 -> ENter 2 element:7

column 2 -> ENter 2 element:9

Enter values for matrix B

column 1 -> ENter 1 element:1

column 2 -> ENter 1 element:2

column 1 -> ENter 2 element:3

column 2 -> ENter 2 element:4


Matrix-A :

[6, 2]

[7, 9]

Matrix-B :

[1, 2]

[3, 4]

Subtraction of Matrix-A and Matrix-B is :

[5, 0]

[4, 5]

Rotate a Matrix by 90 Degrees in python with User input

Rotate a Matrix by 90 Degrees (Clockwise)

Rotating a matrix by 90 degrees in the clockwise direction using python is a very


simple task. You just have to do two simple steps, the first step is to transpose
the given matrix and the second step is to reverse the rows of the transpose
matrix.
Algorithm

 Define a function rotate_matrix(matrix) that takes a matrix as an input.


 Transpose the matrix using the zip function:
 Create an empty list called transposed.
 Iterate over the rows of the matrix (using zip(*matrix)).
 For each row, append a list version of the row to transposed.
 Reverse the rows of the transposed matrix:
 Create an empty list called rotated.
 Iterate over the rows of the transposed matrix.
 For each row, append the reversed row to rotated.
 Return the rotated matrix.

Source Code

def rotate_matrix(matrix):

transposed = []
for row in zip(*matrix):

transposed.append(list(row))

rotated = []

for row in transposed:

rotated.append(row[::-1])

return rotated

rows = int(input('Enter number of rows: '))

cols = int(input('Enter number of column: '))

matrix = [[int(input(f"column {j+1} -> ENter {i+1}


element:")) for j in range(cols)] for i in range(rows) ]

print()

print('Given matrix :')

for row in matrix:

print(row)

rotate_90 = rotate_matrix(matrix)

print()

print('Matrix after rotated by 90 degree')

for row in rotate_90:

print(row)
Output

Enter number of rows: 3

Enter number of column: 3

column 1 -> ENter 1 element:1

column 2 -> ENter 1 element:2

column 3 -> ENter 1 element:3

column 1 -> ENter 2 element:4

column 2 -> ENter 2 element:5

column 3 -> ENter 2 element:6

column 1 -> ENter 3 element:7

column 2 -> ENter 3 element:8

column 3 -> ENter 3 element:9

Given matrix :

[1, 2, 3]

[4, 5, 6]

[7, 8, 9]

Matrix after rotated by 90 degree

[7, 4, 1]

[8, 5, 2]

[9, 6, 3]
Find Inverse of a Matrix Using Numpy

In this post, we will learn how to find inverse of a matrix using numpy with
detailed exaplanation and example.

Mathematically, the inverse of a matrix is only possible if it satisfies the following


conditions:

The matrix should be a square matrix (the number of rows and columns must be
the same)

The determinant of the matrix should be non-zero (det(A) ≠ 0), or you can say
the matrix is non-singular.

Formula to Find Inverse of a Matrix

We are all set to jump into our programming part because we now have a basic
understanding of how to calculate the inverse of a matrix.

All the above information is for your understanding. In the numpy library, there
is one module called linalg (numpy.linalg). Inside that module, there is
one built-in function called inv (numpy.linalg.inv()) that helps us to
invert a matrix very easily in just one line. Let’s see a little more about this
function.
numpy.linalg.inv()

The numpy.linalg.inv() function takes a matrix as input and returns the


inverse of the matrix. It raises an error if the matrix is singular (non-invertible).

Syntax: numpy.linalg.inv(a). where a is your matrix.

Source Code

import numpy as np

n = int(input("Enter size of a matrix: ")) # n x n

matrix = np.array([[int(input(f'column {j+1} -> Enter {i+1}


element:')) for j in range(n)] for i in range(n)])

print("Matrix:")

print(matrix)

inv_matrix = np.linalg.inv(matrix) # inverse the matrix

print("\nInverse of a Matrix:")

print(inv_matrix)

Output

Enter size of a matrix: 2

column 1 -> Enter 1 element:1

column 2 -> Enter 1 element:2

column 1 -> Enter 2 element:3

column 2 -> Enter 2 element:4


Matrix:

[[1 2]

[3 4]]

Inverse of a Matrix:

[[-2. 1. ]

[ 1.5 -0.5]]

Calculate Electricity Bill in Python

Electricity Charges and their rates:

1 to 100 units – 1.5Rs

101 to 200 units – 2.5Rs

201 to 300 units – 4Rs

300 to 350 units – 5Rs

Above 350 – Fixed charge 1500Rs

Now we know electricity charges and their rates, So now let’s start writing our
program.

Source Code

# 1 to 100 units - 1.5Rs

# 101 to 200 units - 2.5Rs


# 201 to 300 units - 4Rs

# 300 to 350 units - 5Rs

# Above 350 - Fixed charge 1500Rs

units = float(input("Enter the Unit Consumed: "))

if units > 0 and units <= 100:

payment = units * 1.5

fixedCharge = 25 # Extra charge

elif units > 100 and units <= 200:

payment = (100 * 1.5) + (units - 100) * 2.5

fixedCharge = 50 # Extra charge

elif units > 200 and units <= 300:

payment = (100 * 1.5) + (200 - 100) * 2.5 + (units -


200) * 4

fixedCharge = 75 # Extra charge

elif units > 300 and units <= 350:

payment = (100 * 1.5) + (200 - 100) * 2.5 + (300 - 200)


* 4 + (units - 300) * 5

fixedCharge = 100 # Extra charge

else:

payment = 0

fixedCharge = 1500

total = payment + fixedCharge


print(f"Your Electricity Bill amount is {total:.2f}")

Output

Enter the Unit Consumed: 275

Your Electricity Bill amount is 775.00

You might also like