NumPy matrix multiplication: Get started in 5 minutes
Tags: tutorial, python, beginners, programming
Published: 2021-09-03 23:02:16

NumPy is a popular Python library that offers a range of powerful mathematical functions. The library is widely used in quantitative fields, such as data science, machine learning, and deep learning. We can use NumPy to perform complex mathematical calculations, such as matrix multiplication. 

Matrix multiplication can help give us quick approximations of very complicated calculations. It can help us with network theory, linear systems of equations, population modeling, and much more. In this tutorial, we’ll explore some basic computations with NumPy matrix multiplication.

Let’s get started!
 
**We'll cover**:
* [What is NumPy?](#numpy)
* [What is a NumPy matrix?](#matrix)
* [NumPy matrix multiplication methods](#methods)
* [Wrapping up and next steps](#nextsteps)

<a name="numpy"></a>
## What is NumPy?
 
NumPy is an open-source Python library that we can use to perform **high-level mathematical operations** with arrays, matrices, linear algebra, Fourier analysis, and more. The NumPy library is very popular within scientific computing, data science, and machine learning. NumPy is compatible with popular data science libraries like pandas, matplotlib, and Scikit-learn. It’s **much faster than Python lists** because it integrates faster codes, such as C and C++, in Python. It also breaks down our tasks into multiple pieces and processes each piece concurrently.
 
### Installing and importing NumPy 

Before we get started, let’s make sure we have NumPy installed. If you already have Python, you can install NumPy with one of the following commands:

```
conda install numpy
```

or 

```
pip install numpy
```

To import NumPy into our Python code, we can use the following command:

```
import numpy as np
```

<br>
 
<a name="matrix"></a>
## What is a NumPy matrix?

A matrix is a 2-D array. Each element in the array has two indices. Let’s look at an example in NumPy:

```
import numpy as np

A = [[6, 7],
      [8, 9]]
 
print(np.array(A) [0,0])

=> 6
```

In the above code, we have matrix A `[[6, 7], [8, 9]]`. We ask for the element given at `(0,0)`, and our output returns `6`. When we want to define the shape of our matrix, we use the number of rows by the number of columns. That means that matrix A has a shape of 2x2.

​Now, let’s take a look at some different NumPy matrix multiplication methods.
<br>
 
<a name="methods"></a>
## NumPy matrix multiplication methods

There are **three main ways** to perform NumPy matrix multiplication:

* `np.dot(array a, array b)`: returns the scalar or dot product of two arrays
* `np.matmul(array a, array b)`: returns the matrix product of two arrays
* `np.multiply(array a, array b)`: returns the element-wise matrix multiplication of two arrays

Let’s take a closer look at each of the three methods:

### Scalar multiplication or dot product with numpy.dot

Scalar multiplication is a simple form of matrix multiplication. A scalar is just a number, like `1`, `2`, or `3`. In scalar multiplication, we **multiply a scalar by a matrix**. Each element in the matrix is multiplied by the scalar, which makes the output the same shape as the original matrix. 

With scalar multiplication, the **order doesn’t matter**. We’ll get the same result whether we multiply the scalar by the matrix or the matrix by the scalar.

Let’s take a look at an example:

```
import numpy as np

A = 5

B = [[6, 7],
      [8, 9]]
 
print(np.dot(A,B))

=> [[30 35]
=>  [40 45]]
```

Now, let’s multiply a 2-dimensional matrix by another 2-dimensional matrix. When multiplying two matrices, the **order matters**. That means that matrix A multiplied by matrix B is not the same as matrix B multiplied by matrix A. 

Before we get started, let's look at a visual for how the multiplication is done.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2e6b8hn164alp27p8img.png)

```
import numpy as np

A = [[6, 7],
      [8, 9]]
      
B = [[1, 3],
      [5, 7]]

print(np.dot(A,B))

print("----------")

print(np.dot(B,A))

=> [[41 67]
=>  [53 87]]
----------
=> [[30 34]
=>  [86 98]]
```

> **Note**: It’s important to note that we can only multiply two matrices if the number of columns in the first matrix is equal to the number of rows in the second matrix.

### Matrix product with numpy.matmul

The `matmul()` function gives us the matrix product of two 2-d arrays. With this method, we can’t use scalar values for our input. If one of our arguments is a 1-d array, the function converts it into a matrix by appending a 1 to its dimension. This is removed after the multiplication is done. 

If one of our arguments is greater than 2-d, the function treats it as a stack of matrices in the last two indexes. The `matmul()` method is great for times when we’re unsure of what the dimensions of our matrices will be. 

Let’s look at some examples:

**Multiplying a 2-d array by another 2-d array**

```
import numpy as np

A = [[2, 4],
      [6, 8]]
      
B = [[1, 3],
      [5, 7]]
 
print(np.matmul(A,B))

=> [[22 34]
=>  [46 74]]
```

**Multiplying a 2-d array by a 1-d array**

```
import numpy as np

A = [[5, 0],
      [0, 5]]
 
B = [5, 2]
 
print(np.matmul(A,B))

=> [25 10]
```

**One array with dimensions greater than 2-d**

```
import numpy as np
 
A = np.arange(8).reshape(2, 2, 2)
 
B = np.arange(4).reshape(2, 2)
 
print(np.matmul(A,B))

=> [[[ 2  3]
=>   [ 6 11]]

=>  [[10 19]
=>   [14 27]]]
```

### Element-wise matrix multiplication with numpy.multiply

The `numpy.multiply()` method takes two matrices as inputs and performs element-wise multiplication on them. Element-wise multiplication, or Hadamard Product, multiples every element of the first matrix by the equivalent element in the second matrix. When using this method, both matrices should have the same dimensions. 

Let’s look at an example:

```
import numpy as np

A = np.array([[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]])

B = np.array([[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]])

print(np.multiply(A,B))

=> [[ 1  6 15 28 45]
=>  [10 16 18 16 10]]
```

We can pass certain rows, columns, or submatrices to the `numpy.multiply()` method. The sizes of the rows, columns, or submatrices that we pass as our operands should be the same. Let’s look at an example:

```
import numpy as np

A = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

B = np.array([[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]])

print(np.multiply(A[ 0,:], B[ 1,: ]))

print("----------")

print(np.multiply(A[ 1,:], B[ 0,:]))

=> [ 16  34  54  76 100]
=> ----------
=> [ 66  84 104 126 150]
```

<a name="nextsteps"></a>
## Wrapping up and next steps

Congrats on taking your first steps with NumPy matrix multiplication! It’s a complicated, yet important part of linear algebra. It helps us further our understanding of different aspects of data science, machine learning, deep learning, and other prevalent fields. There’s still a lot more to learn about NumPy and matrices. Some recommended topics to cover next are:
* NumPy matrix transpose
* NumPy arrays (ndarray)
* NumPy vectorization

To get started learning these concepts and more, check out Educative’s learning path [**Python Data Analysis and Visualization**](https://www.educative.io/path/python-data-analysis). This hands-on learning path will help you master the skills to extract insights from data using a powerful assortment of popular Python libraries. 

*Happy learning!*
<br>
 
### Continue learning about Python
* [50 Python interview questions and answers](https://www.educative.io/blog/python-interview-questions)
* [Data science made simple: 5 essential Scikit-learn tricks](https://www.educative.io/blog/scikit-learn-tricks-tips)
* [Pandas cheat sheet: Top 35 commands and operations](https://www.educative.io/blog/pandas-cheat-sheet)