Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
The Python Workshop Second Edition

You're reading from   The Python Workshop Second Edition Write Python code to solve challenging real-world problems

Arrow left icon
Product type Paperback
Published in Nov 2022
Publisher Packt
ISBN-13 9781804610619
Length 600 pages
Edition 2nd Edition
Languages
Arrow right icon
Authors (5):
Arrow left icon
Mario Corchero Jiménez Mario Corchero Jiménez
Author Profile Icon Mario Corchero Jiménez
Mario Corchero Jiménez
Andrew Bird Andrew Bird
Author Profile Icon Andrew Bird
Andrew Bird
Corey Wade Corey Wade
Author Profile Icon Corey Wade
Corey Wade
Graham Lee Graham Lee
Author Profile Icon Graham Lee
Graham Lee
Dr. Lau Cher Han Dr. Lau Cher Han
Author Profile Icon Dr. Lau Cher Han
Dr. Lau Cher Han
+1 more Show less
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Preface 1. Chapter 1: Python Fundamentals – Math, Strings, Conditionals, and Loops 2. Chapter 2: Python Data Structures FREE CHAPTER 3. Chapter 3: Executing Python – Programs, Algorithms, and Functions 4. Chapter 4: Extending Python, Files, Errors, and Graphs 5. Chapter 5: Constructing Python – Classes and Methods 6. Chapter 6: The Standard Library 7. Chapter 7: Becoming Pythonic 8. Chapter 8: Software Development 9. Chapter 9: Practical Python – Advanced Topics 10. Chapter 10: Data Analytics with pandas and NumPy 11. Chapter 11: Machine Learning 12. Chapter 12: Deep Learning with Python 13. Chapter 13: The Evolution of Python – Discovering New Python Features 14. Index 15. Other Books You May Enjoy

Matrix operations

Let’s learn how to use nested lists to perform basic matrix operations. Although many developers use NumPy to perform matrix operations, it’s very useful to learn how to manipulate matrices using straight Python. First, you will add two matrices in Python. Matrix addition requires both matrices to have the same dimensions; the results will also be of the same dimensions.

In the next exercise, you will perform matrix operations.

Exercise 27 – implementing matrix operations (addition and subtraction)

In this exercise, you will use the matrices in the following figures:

Figure 2.7 – Matrix data for the X matrix

Figure 2.7 – Matrix data for the X matrix

Figure 2.8 – Matrix data for the Y matrix

Figure 2.8 – Matrix data for the Y matrix

Now, let’s add and subtract the X and Y matrices using Python.

The following steps will enable you to complete this exercise:

  1. Open a new Jupyter Notebook.
  2. Create two nested lists, X and Y, to store the values:
    X = [[1,2,3],[4,5,6],[7,8,9]]
    Y = [[10,11,12],[13,14,15],[16,17,18]]
  3. Initialize a 3 x 3 zero matrix called result as a placeholder:
    # Initialize a result placeholder
    result = [[0,0,0],
        [0,0,0],
        [0,0,0]]
  4. Now, implement the algorithm by iterating through the cells and columns of the matrix:
    # 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]
    print(result)

As you learned in the previous section, first, you iterate the rows in the X matrix, then iterate the columns. You do not have to iterate the Y matrix again because both matrices are of the same dimensions. The result of a particular row (denoted by i) and a particular column (denoted by j) equals the sum of the respective row and column in the X and Y matrices.

The output will be as follows:

[[11, 13, 15], [17, 19, 21], [23, 25, 27]]
  1. You can also perform subtraction using two matrices using the same algorithm with a different operator. The idea behind this is the same as in Step 3, except you are doing subtraction. You can implement the following code to try out matrix subtraction:
    X = [[10,11,12],[13,14,15],[16,17,18]]
    Y = [[1,2,3],[4,5,6],[7,8,9]]
    # Initialize a result placeholder
    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]
    print(result)

Here is the output:

[[9, 9, 9], [9, 9, 9], [9, 9, 9]]

In this exercise, you were able to perform basic addition and subtraction using two matrices. In the next section, you will perform multiplication on matrices.

Matrix multiplication operations

Let’s use nested lists to perform matrix multiplication for the two matrices shown in Figures 2.9 and 2.10:

Figure 2.9 – The data of the X matrix

Figure 2.9 – The data of the X matrix

Figure 2.10 – The data of the Y matrix

Figure 2.10 – The data of the Y matrix

For matrix multiplication, the number of columns in the first matrix (X) must equal the number of rows in the second matrix (Y). The result will have the same number of rows as the first matrix and the same number of columns as the second matrix. In this case, the resulting matrix will be a 3 x 4 matrix.

Exercise 28 – implementing matrix operations (multiplication)

In this exercise, your end goal will be to multiply two matrices, X and Y, and get an output value. The following steps will enable you to complete this exercise:

  1. Open a new Jupyter notebook.
  2. Create two nested lists, X and Y, to store the value of the X and Y matrices:
    X = [[1, 2], [4, 5], [3, 6]]
    Y = [[1,2,3,4],[5,6,7,8]]
  3. Create a zero-matrix placeholder to store the result:
    result = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
  4. Implement the matrix multiplication algorithm to compute the result:
    # iterating by row of X
    for i in range(len(X)):
      # iterating by column by Y
      for j in range(len(Y[0])):
        # iterating by rows of Y
        for k in range(len(Y)):
          result[i][j] += X[i][k] * Y[k][j]

You may have noticed that this algorithm is slightly different from the one you used in Step 3 of Exercise 27 – implementing matrix operations (addition and subtraction). This is because you need to iterate the rows of the second matrix, Y, as the matrices have different shapes, which is what is mentioned in the preceding code snippet.

  1. Now, print the final result:
    for r in result:
      print(r)

Let’s look at the output:

Figure 2.11 – Output of multiplying the X and Y matrices

Figure 2.11 – Output of multiplying the X and Y matrices

Note

To review the packages that data scientists use to perform matrix calculations, such as NumPy, check out https://docs.scipy.org/doc/numpy/.

In the next section, you will work with and learn about a new data structure: Python dictionaries.

You have been reading a chapter from
The Python Workshop Second Edition - Second Edition
Published in: Nov 2022
Publisher: Packt
ISBN-13: 9781804610619
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime