Python 3, an illustrated tour Transcripts
Chapter: Classes and inheritance
Lecture: Matrix Multiplication

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Pep 465 introduced what's called the matrix multiplication operator
0:05 this came out in Python 3.5,
0:07 from the pep we read: in numerical code there are two important operations,
0:12 which compete for use of Python's asterisk operator
0:15 element wise multiplication and matrix multiplication.
0:19 Here's an example of doing matrix multiplication.
0:23 If you're familiar with linear algebra, this is a common operation.
0:26 Here I'm importing the numpy library and I'm creating 2 arrays
0:30 and then I'm looping over the pairs of elements and multiplying them together
0:35 and summing the result.
0:37 This is doing what's called matrix multiplication.
0:40 It gives me in this case 285 as the result.
0:43 This pep introduced an operation to do that
0:45 and we can use the @ sign around the two arrays
0:49 and that also gives us the same result 285.
0:52 Note that this is different than multiplication,
0:55 if we simply multiply the array in numpy
0:58 this is going to do what is called element wise multiplication
1:01 and in that case, it will multiply every element in the array by 10,
1:05 it won't do multiplication of the whole element by 10 per se.
1:11 If you want to have a class that implements matrix multiplication
1:15 you just need to implement the __matmul__ operator.
1:20 Again, in Python, everything is an object and there are various protocols
1:24 and if we follow certain protocols, we can take advantage of certain behavior.
1:27 In this case, if we want to be able to use the @ sign
1:31 we can Implement __matmul__.
1:33 This case is pretty dumb example
1:35 it simply ignores the other that's passed in there and returns 42,
1:40 but you could do something more smart if you want to.
1:42 If you're not familiar with dunder methods
1:45 what's happening is self here would be a and b would come in as other
1:51 and so inside of that method there, you could do whatever you wanted to
1:55 with them and you could Implement that operation.