Posts about Matrix

Calculate The Trace Of A Matrix

Goal

This post aims to show how to calculate the trace of a matrix using numpy i.e., $tr(A)$

$tr(A)$ is defined as

$$ tr(A) = \sum_{i=1}^{n} a_{ii} = a_{11} + a_{22} + \cdots + a_{nn} $$

Reference:

Libraries

In [1]:
import numpy as np

Create a matrix

In [2]:
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
arr
Out[2]:
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

Calculate the trace

In [4]:
arr.trace()
Out[4]:
15
In [7]:
sum([arr[i, i] for i in range(len(arr))])
Out[7]:
15

Create A Sparse Matrix

Goal

This post aims to create a sparse matrix in python using following modules:

  • Numpy
  • Scipy

Reference:

  • Scipy Document
  • Chris Albon's blog (I look at his post's title and wrote my own contents to deepen my understanding about the topic.)

Library

In [8]:
import numpy as np
import scipy.sparse

Create a sparse matrix using csr_matrix

CSR stands for "Compressed Sparse Row" matrix

In [9]:
nrow = 10000
ncol = 10000

# CSR stands for "Compressed Sparse Row" matrix
arr_sparse = scipy.sparse.csr_matrix((nrow, ncol))
arr_sparse
Out[9]:
<10000x10000 sparse matrix of type '<class 'numpy.float64'>'
	with 0 stored elements in Compressed Sparse Row format>