Matrix Methods
Matrix Methods
operation
“
Goal of this document is to teach you the basics of
matrix. Specially to create a matrix; understanding their
mathematical - addition, subtraction,
multiplication, inversion; statistical properties – mean,
max, variance, standard deviation, and their properties –
determinant, trace, eigenvalue, eigenvector; and many
more.
Document in a Glance:
1.1: Creating a Matrix
1.2: Creating a Sparse Matrix
1.3: Selecting Elements of Matrix
1.4: Shape, Size, and dimension of Matrix
1.5: Operation with Matrix
1.6: Statistics of a Matrix
1.7: Reshaping the matrix
1.8: Transposing a Matrix and a vector
1.9: Flattening a Matrix
1.10: Rank and Determinant of a Matrix
1.11: Diagonal of a Matrix
1.12: Trace of a Matrix
1.13: Getting Eigenvalues and Eigenvectors
1.14: Adding and Subtracting Matrices
1.15: Product of the Matrices
1.16: Inverting a Matrix
1.17: Generating Random values
1
Ref: developed with the help of online study material for Python
1.1 Creating a Matrix: We can create a matrix using NumPy. First we create a row and
column vector using array method of NumPy.
>>> print(vector_row)
[4 5 6]
2
Ref: developed with the help of online study material for Python
1.2 Creating a Sparse Matrix:
Sometimes in the scientific data most of the elements in the data are zeros. That is the
given data with very few nonzero values, and we want to efficiently represent it. We
can use the sparse, a method of SciPy which only store nonzero elements and assume
all other values will be zero, leading to significant computational savings. If we view
the sparse matrix we can see that only the nonzero values are stored:
>>>import numpy as np
>>>from scipy import sparse
There are a number of types of sparse matrices. However, in compressed sparse row (CSR)
matrices, (1, 1) and (2, 0) represent indices of the zero-indexed (index of the first
element is zero, not one) non-zero values 4 and 5, respectively. For example, the
element 4 is in the second row and second column. We can see the advantage of
sparse matrices if we create a much larger matrix with many more zero elements and
then compare this larger matrix with our original sparse matrix:
3
Ref: developed with the help of online study material for Python
>>>print(matrix_large_sparse)
(1, 1) 1
(2, 0) 3
As we can see, despite the fact that we added many more zero elements in the larger
matrix, its sparse representation is exactly the same as our original sparse matrix. That
is, the addition of zero elements did not change the size of the sparse matrix.
>>>import numpy as np
# Create row vector
>>>vector = np.array([1, 2, 3, 4, 5, 6])
# Create matrix
>>>matrix = np.array([[5, 1, 3],
[4, 5, 6],
[7, 8, 9]])
>>>import numpy as np
# Create matrix
>>>matrix = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
>>>import numpy as np
5
Ref: developed with the help of online study material for Python
# Create matrix
>>>matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>>print(matrix+100)
[[101 102 103]
[104 105 106]
[107 108 109]]
>>>print(matrix*100)
[[100 200 300]
[400 500 600]
[700 800 900]]
>>>print(matrix/100)
[[0.01 0.02 0.03]
[0.04 0.05 0.06]
[0.07 0.08 0.09]]
>>>print(matrix//2)
[[0 1 1]
[2 2 3]
[3 4 4]]
>>>print(matrix%2)
[[1 0 1]
[0 1 0]
[1 0 1]]
>>>import numpy as np
6
Ref: developed with the help of online study material for Python
# Create matrix
>>>matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
Most of the time it is required to know the statistics of the matrix data; mean, variance
and standard deviation and can be easily calculated using numpy.
7
Ref: developed with the help of online study material for Python
1.7 Reshaping the matrix:
Reshaping allow to change the shape i. e. the number of rows and columns of a
matrix without changing the element values. reshape allows us to restructure a matrix
so that the data remain maintained it is organized as in a different number of rows
and columns. The only requirement is that the shape of the original and new matrix
contains the same number of elements. We can check this by finding the size of a
matrix using size:
>>>import numpy as np
# Create 4x3 matrix
>>>matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]])
>>>matrix.size
12
One useful argument in reshape is -1, which effectively means “as many as needed,”
so reshape(-1, 1) means one row and as many columns as needed:
>>>matrix.reshape(1, -1)
array([[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]])
Finally, if we provide one integer, reshape will return a 1D array of that length:
>>>matrix.reshape(12)
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
8
Ref: developed with the help of online study material for Python
1.8 Transposing a Matrix and a vector:
In transposing operation column and row indices of each element are interchanged.
Technically, a vector cannot be transposed because it is just a collection of values.
However, it is common practice to transposing a vector is the nothing but converting
a row vector to a column vector or vice versa: For transposing in python the method
is known as T method:
>>>import numpy as np
>>>matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
9
Ref: developed with the help of online study material for Python
method reshape is already discussed in the previous section, now the discussion is
about flatten.
import numpy as np
>>>matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>>matrix.reshape(1, -1)
array([[1, 2, 3, 4, 5, 6, 7, 8, 9]])
>>>matrix.reshape(9)
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
import numpy as np
>>>matrix np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# find the matrix rank
>>>np.linalg.matrix_rank(matrix)
2
10
Ref: developed with the help of online study material for Python
1.11 Diagonal of a Matrix:
It is also possible to get a diagonal element using diagonal method and the off diagonal
element using offset method along with diagonal method.
>>>import numpy as np
>>>matrix np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# finding diagonal two below and two above the main diagonal
>>> matrix.diagonal(offset=-2)
array([7])
>>> matrix.diagonal(offset=2)
array([3])
>>>import numpy as np
>>>matrix np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
11
Ref: developed with the help of online study material for Python
# calculate the trace
>>>matrix.trace()
15
# Finding the diagonal and then sum of the elements
>>>sum(matrix.diagonal())
15
>>>import numpy as np
>>>matrix np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# View eigenvalues
>>>eigenvalues
array([ 1.61168440e+01, -1.11684397e+00, -1.30367773e-15])
# View eigenvectors
>>>eigenvectors
array([[-0.23197069, -0.78583024, 0.40824829],
[-0.52532209, -0.08675134, -0.81649658],
[-0.8186735, 0.61232756, 0.40824829]])
12
Ref: developed with the help of online study material for Python
>>>import numpy as np
>>>matrix_a = np.array([[1, 1, 1],
[1, 1, 1],
[1, 1, 2]])
>>>matrix_b = np.array([[1, 3, 1],
[1, 3, 1],
[1, 3, 8]])
# Add two matrices
>>>np.add(matrix_a, matrix_b)
array([[ 2, 4, 2],
[ 2, 4, 2],
[ 2, 4, 10]])
# Subtract two matrices
>>>np.subtract(matrix_a, matrix_b)
array([[ 0, -2, 0],
[ 0, -2, 0],
[ 0, -2, -6]])
# Alternative way to Add two matrices
>>>matrix_a + matrix_b
array([[ 2, 4, 2],
[ 2, 4, 2],
[ 2, 4, 10]])
Where ai and bi are the ith element of vector a and b. We can use NumPy’s dot (.) class
to calculate the dot product. Alternatively, we can use the new @ operator:
>>>import numpy as np
13
Ref: developed with the help of online study material for Python
>>>np.dot(vector_a, vector_b)
32
#Alternative way to calculate dot product
>>>vector_a @ vector_b
32
14
Ref: developed with the help of online study material for Python
1.16 Inverting a Matrix:
The inverse of a square matrix, A, is also a matrix A–1, such that:
>>>import numpy as np
# Create matrix
>>>matrix = np.array([[1, 4],
[2, 5]])
15
Ref: developed with the help of online study material for Python
# Draw three numbers from a logistic distribution with mean 0.0 #and scale of 1.0
>>>np.random.logistic(0.0, 1.0, 3)
array([-0.98118713, -0.08939902, 1.46416405])
# Draw three numbers greater than or equal to 1.0 and less than 2.0
>>>np.random.uniform(1.0, 2.0, 3)
array([ 1.47997717, 1.3927848 , 1.83607876])
Finally, it can sometimes be useful to return the same random numbers for multiple
times to get predictable, repeatable results. We can do this by setting the “seed” (an
integer) of the pseudorandom generator. Random processes with the same seed will
always produce the same output.
>>> np.random.seed(0)
>>> np.random.random(4)
array([0.5488135 , 0.71518937, 0.60276338, 0.54488318])
# without seed
>>> np.random.random(4)
array([0.4236548 , 0.64589411, 0.43758721, 0.891773 ])
16
Ref: developed with the help of online study material for Python