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 this came out in Python 3.5,
0:08 from the pep we read: in numerical code there are two important operations, which compete for use of Python's asterisk operator
0:16 element wise multiplication and matrix multiplication. Here's an example of doing matrix multiplication.
0:24 If you're familiar with linear algebra, this is a common operation. Here I'm importing the numpy library and I'm creating 2 arrays
0:31 and then I'm looping over the pairs of elements and multiplying them together and summing the result.
0:38 This is doing what's called matrix multiplication. It gives me in this case 285 as the result. This pep introduced an operation to do that
0:46 and we can use the @ sign around the two arrays and that also gives us the same result 285. Note that this is different than multiplication,
0:56 if we simply multiply the array in numpy this is going to do what is called element wise multiplication
1:02 and in that case, it will multiply every element in the array by 10, it won't do multiplication of the whole element by 10 per se.
1:12 If you want to have a class that implements matrix multiplication you just need to implement the __matmul__ operator.
1:21 Again, in Python, everything is an object and there are various protocols
1:25 and if we follow certain protocols, we can take advantage of certain behavior. In this case, if we want to be able to use the @ sign
1:32 we can Implement __matmul__. This case is pretty dumb example it simply ignores the other that's passed in there and returns 42,
1:41 but you could do something more smart if you want to. If you're not familiar with dunder methods
1:46 what's happening is self here would be a and b would come in as other and so inside of that method there, you could do whatever you wanted to
1:56 with them and you could Implement that operation.


Talk Python's Mastodon Michael Kennedy's Mastodon