Matrix multiplication using NumPy

By xngo on March 5, 2019

Overview

NumPy is a Python library that provides a way to manipulate multidimensional arrays faster and easier. I learned today that you can multiple NumPy array with a scalar value as easy as this: [1,2,3]*4. I still don't understand why it works when you can't do this using Python's list(). It is awesome! I now understand why Python is so popular among scientists.

Multiply matrix

Suppose you want to multiple the following matrix:

[1,2,3]   [0]
[4,5,6] * [1]
[7,8,9]   [2]

You write it in Python using Numpy like the following:

import numpy as np
 
m = np.array([[1,2,3],[4,5,6],[7,8,9]])
c = np.array([0,1,2])
results= m * c[:, np.newaxis]
 
print(results)

The output

[[ 0  0  0]
 [ 4  5  6]
 [14 16 18]]

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.