Python Matrix Operations (Addition & Multiplication

Aim: i)Write a python program that defines a matrix and prints

Program:

# A basic code for matrix input from user

R = int(input("Enter the number of rows:"))
C = int(input("Enter the number of columns:"))

# Initialize matrix
matrix= []
print("Enter the entries rowwise:")

# For user input
for i in range(R):     # A for loop for row entries
   a =[]
   for j in range(C):  # A for loop for column entries
      a. append(int(input()))
   matrix. append(a)

# For printing the matrix
print("the matrix is")
for i in range(R):
   for j in range(C):
      print(matrix[i][j], end = " ")
   print()

Output:

Enter the number of rows:3
Enter the number of columns:3
Enter the entries row wise:
3
2
1
6
5
4
9
8
7
the matrix is
3 2 1
6 5 4
9 8 7

Aim: ii)Write a python program to perform addition of two square matrices

Program:

# Program to add two matrices using nested loop

X = [[1,2,3],
   [4 ,5,6],
   [7 ,8,9]]

Y = [[9,8,7],
   [6,5,4],
   [3,2,1]]


result = [[0,0,0],
      [0,0,0],
      [0,0,0]]

# iterate through rows
for i in range(len(X)):
# iterate through columns
   for j in range(len(X[0])):
      result[i][j] = X[i][j] + Y[i][j]

for r in result:
   print(r)

Output:

[10, 10, 10]
[10, 10, 10]
[10, 10, 10]

Aim:iii)Write a python program to perform multiplication of two square matrices

Program:

# Program to multiply two matrices using nested loops

# 3x3 matrix
X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
    [6,7,3,0],
    [4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
         [0,0,0,0],
         [0,0,0,0]]

# iterate through rows of X
for i in range(len(X)):
   # iterate through columns of Y
   for j in range(len(Y[0])):
       # iterate through rows of Y
       for k in range(len(Y)):
           result[i][j] += X[i][k] * Y[k][j]

for r in result:
   print(r)

Output:

[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]

Sample Viva Questions and Answers

  1. What is a matrix in mathematics?
    A matrix is a rectangular array of numbers arranged in rows and columns, used to represent data or mathematical concepts.

  2. What is the purpose of the matrix multiplication program?
    The program performs multiplication of two square matrices, resulting in a new matrix that represents the product of the two input matrices.

  3. What are the conditions for multiplying two matrices?
    The number of columns in the first matrix must equal the number of rows in the second matrix. For square matrices, this means they must have the same dimensions.

  4. What is the purpose of the matrix addition program?
    The program adds two square matrices element-wise, producing a new matrix where each element is the sum of the corresponding elements from the input matrices.

  5. What are the conditions for adding two matrices?
    The two matrices must have the same dimensions (i.e., the same number of rows and columns) to be added together.

  6. How can you define a matrix in Python?
    A matrix can be defined in Python using nested lists, where each inner list represents a row of the matrix.

  7. What is the significance of printing a matrix?
    Printing a matrix allows users to visualize the data it contains, making it easier to verify the results of operations like addition and multiplication.

  8. What libraries can be used for matrix operations in Python?
    Libraries such as NumPy provide efficient tools for performing matrix operations, including addition and multiplication.

  9. How does the time complexity of matrix multiplication compare to addition?
    Matrix multiplication generally has a higher time complexity (O(n^3) for naive algorithms) compared to matrix addition, which is O(n^2).

  10. What are some practical applications of matrix operations?
    Matrix operations are widely used in various fields, including computer graphics, machine learning, data analysis, and scientific computing.

๐Ÿ“Œ Python Programming Lab – Complete Guide

Welcome to the Python Programming Lab! This comprehensive lab series is designed to provide a solid foundation in Python programming through practical exercises and hands-on learning. From basic calculations to advanced concepts like file handling, modules, and GUI programming, this lab covers it all. Letโ€™s dive into what youโ€™ll be learning throughout this lab course.


๐Ÿ” Week 1: Introduction to Python Basics

In the first week, you will explore fundamental Python concepts aimed at building a strong foundation for your programming journey.

  • Getting Started with Python: Visit the Python Official Website to explore documentation and use the help() function in the interpreter.
  • Python as a Calculator: Learn how to perform basic arithmetic operations like addition, subtraction, multiplication, and division.
  • Calculating Compound Interest: Write a program to calculate compound interest using the formula with given principal, rate, and time.
  • Distance Calculation: Compute the distance between two points using the distance formula.
  • Reading User Details: Write a program to collect and print user details like name, address, email, and phone number.

๐Ÿ” Week 2: Python Loops and Conditional Statements

This week focuses on using loops and conditional statements effectively.

  • Pattern Generation: Print a triangle pattern using nested loops.
  • Character Identification: Write a program to identify whether the input is a digit, lowercase, uppercase, or special character.
  • Fibonacci Sequence Generation: Use a while loop to generate the Fibonacci series.
  • Prime Numbers Identification: Find all prime numbers within a specified range using the break statement.

๐Ÿ” Week 3: Data Structures and Functions

Dive into data structures and creating functions to enhance your programming skills.

  • Converting Lists and Tuples to Arrays: Understand how to convert different data structures.
  • Finding Common Values: Compare two arrays to find common values.
  • Calculating GCD: Create a function to calculate the greatest common divisor (GCD) of two numbers.
  • Palindrome Checker: Write a function that checks if a given string is a palindrome.

๐Ÿ” Week 4: Advanced Functions and String Manipulation

This week emphasizes sorting, handling duplicate elements, and manipulating strings effectively.

  • Checking Sorted Lists: Write a function to check if a list is sorted.
  • Handling Duplicates: Create functions to detect and remove duplicates from lists.
  • Dictionary Inversion: Write a program to swap keys and values in a dictionary.
  • String Manipulation: Add commas between characters, remove words from strings, and convert sentences to title case without using built-in functions.
  • Binary String Generation: Use recursion to generate all binary strings of a specified length.

๐Ÿ” Week 5: Working with Matrices and Modules

Learn to work with matrices and create custom modules for various applications.

  • Matrix Operations: Define, print, add, and multiply square matrices using Python.
  • Creating Modules: Build modules using geometrical shapes and their operations.
  • Exception Handling: Implement exception handling for robust error management.

๐Ÿ” Week 6: Object-Oriented Programming and Validation

This week focuses on using classes, inheritance, and validation techniques.

  • Drawing Shapes with Classes:
    • Create classes for rectangles, points, and circles, and draw them on a canvas.
    • Add colors and attributes to these shapes to enhance visualization.
  • Method Resolution Order (MRO): Demonstrate MRO in multiple inheritance scenarios.
  • Data Validation: Write programs to validate phone numbers and email addresses.

๐Ÿ” Week 7: File Handling and Text Processing

Master file handling techniques and analyzing text data.

  • File Merging: Combine the contents of two files into a new file.
  • Word Search: Create a function to find specific words in a file.
  • Word Frequency Analysis: Identify the most frequent words in a text file.
  • Text Statistics: Count words, vowels, blank spaces, lowercase, and uppercase letters in a file.

๐Ÿ” Week 8: Python Libraries and GUI Programming

Explore advanced Python libraries and build simple graphical user interfaces.

  • NumPy, Plotly, and Scipy: Learn how to install and use these powerful libraries for data analysis and visualization.
  • Digital Logic Gates: Implement logic gate operations such as AND, OR, NOT, and EX-OR.
  • Adder Circuits: Create programs for Half Adders, Full Adders, and Parallel Adders.
  • GUI Programming: Build a simple window wizard with text labels, input fields, and buttons using Python’s GUI tools.

๐ŸŒŸ Conclusion:

The Python Programming Lab R23 provides you with a strong foundation in Python programming through a wide range of exercises, from basic concepts to advanced topics. By the end of this lab, you will have gained valuable skills in data processing, file handling, OOP, modules, and GUI development. Start coding and enhance your Python skills! ๐Ÿš€


;