import numpy as np
2 Introduction to NumPy
2.1 Introduction
NumPy provides (i) array objects for storing homogeneous data, (ii) mathematical functions for arrays, (iii) linear algebra functions, and (iv) statistical functions for generating random numbers. We constrain our treatment of NumPy to features that are useful for econometric analysis. The NumPy module is usually imported under the alias np
, as shown in the following chunk.
\[ \DeclareMathOperator{\cov}{cov} \DeclareMathOperator{\corr}{corr} \DeclareMathOperator{\var}{var} \DeclareMathOperator{\SE}{SE} \DeclareMathOperator{\E}{E} \DeclareMathOperator{\A}{\boldsymbol{A}} \DeclareMathOperator{\x}{\boldsymbol{x}} \DeclareMathOperator{\sgn}{sgn} \DeclareMathOperator{\argmin}{argmin} \newcommand{\tr}{\text{tr}} \newcommand{\bs}{\boldsymbol} \newcommand{\mb}{\mathbb} \]
2.2 Arrays
An array can be considered as a container for data of the same type. Arrays can be initialized from lists (or tuples) using the np.array
function.
# Initialize an array from a list
= [0.0, 1, 2, 3, 4]
x = np.array(x)
y type(y)
numpy.ndarray
y
array([0., 1., 2., 3., 4.])
Attributes of an array include ndim
(the number of dimension), shape
(the size of each dimension), size
(the total number of elements), and dtype
(the data type). Consider the following examples:
= np.array([0.0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
y
y# The size of each dimension
y.shape # The number of dimensions
y.ndim # The total number of elements
y.size # The data type of the elements y.dtype
array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
(10,)
1
10
dtype('float64')
We can create row vectors from 1-dimensional arrays. For example, \(x = [1,2,3]\) can be entered as
= np.array([1, 2, 3])
x
x
x.shape x.ndim
array([1, 2, 3])
(3,)
1
Nested lists can be used to create higher-dimensional arrays. The number of dimensions is determined by the level of nesting. A simple list creates a one-dimensional array. A two-dimensional array requires a nested list with one level of nesting. Higher-dimensional arrays require additional levels of nesting. Some examples are provided below.
# A 2-dimensional array
= np.array([[1, 2, 3], [2, 3, 10]])
x
x
x.shape
x.ndim x.size
array([[ 1, 2, 3],
[ 2, 3, 10]])
(2, 3)
2
6
# A 3-dimensional array
= np.array([[[1, 2, 3, 4.6]]])
x
x
x.shape
x.ndim x.size
array([[[1. , 2. , 3. , 4.6]]])
(1, 1, 4)
3
4
Matrices are two dimensional arrays. Matrices follow the rules of linear algebra. We can use the np.matrix()
function on an array-like objects to create matrices. Alternatively, the np.mat()
or np.asmatrix()
functions can be used to coerce an array into a matrix.
# A 1x3 matrix
= np.matrix([1, 2, 3])
x
xtype(x)
x.shape x.ndim
matrix([[1, 2, 3]])
numpy.matrix
(1, 3)
2
# A 1x5 matrix
= [0.0, 1, 2, 3, 4]
x = np.asmatrix(x)
y type(y)
y.shape y.ndim
numpy.matrix
(1, 5)
2
The column vector \(x=(12,13,3,5)^{'}\) can be created in the following way.
# As 4x1 array
= np.array([[12], [13], [3], [5]])
x
x
x.shape np.ndim(x)
array([[12],
[13],
[ 3],
[ 5]])
(4, 1)
2
# As 4x1 matrix
= np.matrix([[12], [13], [3], [5]])
x
x
x.shape np.ndim(x)
matrix([[12],
[13],
[ 3],
[ 5]])
(4, 1)
2
Suppose that we want to create a 3x2x2
array. You can think this object in the following way: we have three pages and on each page we have a 2x2
array.
# A 3x2x2 array
= np.array([[[2, 1], [2, 3]], [[3, 2], [5, 6]], [[5, 3], [10, 11]]])
y
y
y.shape y.ndim
array([[[ 2, 1],
[ 2, 3]],
[[ 3, 2],
[ 5, 6]],
[[ 5, 3],
[10, 11]]])
(3, 2, 2)
3
2.3 Special arrays
Some useful functions to create special arrays are listed below.
np.ones()
: Generates an array of ones and is generally called with one argument, a tuple, containing the size of each dimension.np.ones_like()
: Creates an array with the same shape and data type as the input.ones_like(x)
is equivalent to callingnp.ones(x.shape,x.dtype)
.np.zeros()
: Produces an array of zeros in the same waynp.ones()
.np.zeros_like()
: Creates an array with the same size and shape as the input.zeros_like(x)
is equivalent to callingnp.zeros(x.shape,x.dtype)
.np.empty()
: Produces an empty (uninitialized) array.np.empty_like()
: Creates an array with the same size and shape as the input.np.empty_like(x)
is equivalent to callingnp.empty(x.shape,x.dtype)
.np.eye()
,np.identity()
: Generates an identity array.np.linspace(l,u,n)
: Generates a set ofn
points uniformly spaced betweenl
(inclusive) andu
(inclusive).np.arange(l,u,s)
: Produces a set of points spaced bys
betweenl
(inclusive) andu
(exclusive).
Some illustrative examples are given below.
# Create a 3x2 array of ones
= 3, 2
M, N = np.ones((M, N))
x x
array([[1., 1.],
[1., 1.],
[1., 1.]])
# Create a 3x3x2 array of ones
= np.ones((M, M, N))
x x
array([[[1., 1.],
[1., 1.],
[1., 1.]],
[[1., 1.],
[1., 1.],
[1., 1.]],
[[1., 1.],
[1., 1.],
[1., 1.]]])
# Create a 3x2 array of 32-bit integers
= np.ones((M, N), dtype = "int32")
x x
array([[1, 1],
[1, 1],
[1, 1]])
# Create a 3x2 array of zeros
= np.zeros((M, N))
x x
array([[0., 0.],
[0., 0.],
[0., 0.]])
# Create a 2x3x5 array of zeros
= 3, 5
M, N = np.zeros((2, M, N))
x x
array([[[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]],
[[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]]])
# Create a 3x5 array of 64-bit integers
= np.zeros((M, N), dtype="int64")
x x
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]], dtype=int64)
# Create a 3x5 empty array
= np.empty((M, N))
x x
array([[0.00000000e+000, 0.00000000e+000, 0.00000000e+000,
0.00000000e+000, 0.00000000e+000],
[0.00000000e+000, 0.00000000e+000, 0.00000000e+000,
0.00000000e+000, 0.00000000e+000],
[0.00000000e+000, 0.00000000e+000, 0.00000000e+000,
0.00000000e+000, 6.81019663e-310]])
# Create the 5x5 identity array
= np.eye(5)
In In
array([[1., 0., 0., 0., 0.],
[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 1.]])
# Create an array of 5 points uniformly spaced between 1 (inclusive) and 11 (exclusive)
= np.linspace(1, 11, 5)
z z
array([ 1. , 3.5, 6. , 8.5, 11. ])
# Create set of points spaced by 2 between 3 (inclusive) and 11 (exclusive)
= np.arange(3, 11, 2)
x x
array([3, 5, 7, 9])
2.4 Accessing elements of an array
There are four methods for accessing elements in an array:
- Scalar selection: Accesses individual elements using their indices.
- Slicing: Retrieves a subset of the array by specifying a range of indices.
- Numerical indexing: Uses arrays of integers to access multiple specific elements.
- Logical (or Boolean) indexing: Uses Boolean arrays to select elements that satisfy certain conditions.
Scalar selection is implemented using [i]
for 1-dimensional arrays, [i,j]
for 2-dimensional arrays and [i_1,i_2,...,i_n]
for general n-dimensional arrays. Some illustrative examples are given below.
= np.array([1.0, 2.0, 3.0, 4.0, 5.0])
x 0] # returns the first element x[
1.0
= np.array([[1.0, 2, 3], [4, 5, 6]])
x
x1, 2] # returns the element on the second row and the third column x[
array([[1., 2., 3.],
[4., 5., 6.]])
6.0
= np.array([1.0, 2.0, 3.0, 4.0, 5.0])
x 0] = -5 # assign -5 to the first element
x[ x
array([-5., 2., 3., 4., 5.])
Arrays are sliced using the syntax [:,:,...,:]
, where the number of dimensions of the arrays determines the size of the slice.
[:]
and[::]
are the same as[0:n:1]
, wheren
is the length of the array (or list).[a:]
and[a:n]
are the same as[a:n:1]
, wheren
is the length of the array (or list).[:b]
is the same as[0:b:1]
.[::s]
is the same as[0:n:s]
, wheren
is the length of the array (or list).
Some illustrative examples are given below.
= np.array([1.0, 2.0, 3.0, 4.0, 5.0])
x = x[:]
y y
array([1., 2., 3., 4., 5.])
= x[:2] # first two elements
y y
array([1., 2.])
3:] # elements after index 3 x[
array([4., 5.])
= x[1::2] # every second element, starting at index 1
y y
array([2., 4.])
= np.array([[0.0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])
y
y1, :] # first row, all columns y[:
array([[0., 1., 2., 3., 4.],
[5., 6., 7., 8., 9.]])
array([[0., 1., 2., 3., 4.]])
1] # all rows, first column y[:, :
array([[0.],
[5.]])
1, 0:3] # Row 0, columns 0 to 2 y[:
array([[0., 1., 2.]])
3:] # All rows, columns 3 and 4 y[:,
array([[3., 4.],
[8., 9.]])
Logical indexing uses the Boolean arrays for selection.
= np.array([[0.0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])
y = y > 6
z z
array([[False, False, False, False, False],
[False, False, True, True, True]])
= 99 # setting elements that are bigger than 6 to 99
y[z] y
array([[ 0., 1., 2., 3., 4.],
[ 5., 6., 99., 99., 99.]])
2.5 Numerical operations on arrays and matrices
Arrays addition, subtraction, devision, exponentiation, and multiplication are performed element-wise. For matrix multiplication, the @
infix operator, the dot
method, or the np.dot
function can be used. Matrix transpose can be performed using the x.T
attribute, the x.transpose
method, or the np.transpose
function. Some illustrative examples are given below.
= np.array([[1.0, 2], [3, 2], [3, 4]])
x
x= np.array([[9.0, 8], [7, 6]])
y y
array([[1., 2.],
[3., 2.],
[3., 4.]])
array([[9., 8.],
[7., 6.]])
@ y # matrix multiplication x
array([[23., 20.],
[41., 36.],
[55., 48.]])
# matrix multiplication x.dot(y)
array([[23., 20.],
[41., 36.],
[55., 48.]])
# matrix multiplication np.dot(x, y)
array([[23., 20.],
[41., 36.],
[55., 48.]])
* 2 # element-wise squaring x
array([[2., 4.],
[6., 4.],
[6., 8.]])
= np.matrix([[1, 2, 4], [5, 7, 10]])
z
z# using the np.transpose() function np.transpose(z)
matrix([[ 1, 2, 4],
[ 5, 7, 10]])
matrix([[ 1, 5],
[ 2, 7],
[ 4, 10]])
# using the transpose attribute z.T
matrix([[ 1, 5],
[ 2, 7],
[ 4, 10]])
# using the transpose method z.transpose()
matrix([[ 1, 5],
[ 2, 7],
[ 4, 10]])
Comparison operators can be used to compare arrays of the same size. These operations yield Boolean arrays of the same size:
= np.array([[1, 2, 45, 6], [3, 4, 34, 6]])
x = np.array([[10, 2.5, 45, 1.4], [7, 4, 20, 60]])
y < y x
array([[ True, True, False, False],
[ True, False, False, True]])
We list some useful functions for mathematical operations below. For more information, see Mathematical functions from the NumPy documentation.
np.sum()
/np.cumsum()
: Returns the sum of elements in an array / the cumulative sum of the values in the array.np.prod()
/np.cumprod()
: Returns the product / cumulative product of the elements in the array.np.diff()
: Calculates the n-th discrete difference along the given axis.np.exp()
: Returns the element-wise exponential (\(e^x\)) of the array.np.log()
: Returns the element-wise natural logarithm (\(\ln(x)\)) of the array.np.log10()
: Returns the element-wise base-10 logarithm (\(\log_{10}(x)\)) of the array.np.sqrt()
: Returns the element-wise square root (\(\sqrt{x}\)) of the array.np.square()
: Returns the element-wise square (\(x^2\)) of the array.np.absolute()
,abs()
: Returns the element-wise absolute value of the array.np.sign()
: Returns the element-wise sign of the values in the array.
Some illustrative examples are presented below.
# Generate 3x4 array of draws from N(0,1)
= np.random.randn(3, 4)
x x
array([[ 0.14414527, 1.67604949, -1.24497237, 0.72010628],
[ 1.34116891, 0.15584517, 0.18443319, -1.15496347],
[ 1.71307086, 0.54520754, -0.3696638 , -0.44438394]])
sum(x) # sum of all elements np.
3.2660431332988744
sum(x, 0) # sum of columns, 4 elements np.
array([ 3.19838504, 2.37710219, -1.43020298, -0.87924112])
sum(x, 1) # sum of rows, 3 elements np.
array([1.29532867, 0.5264838 , 1.44423066])
0) # cumulative sum of columns np.cumsum(x,
array([[ 0.14414527, 1.67604949, -1.24497237, 0.72010628],
[ 1.48531418, 1.83189466, -1.06053918, -0.43485719],
[ 3.19838504, 2.37710219, -1.43020298, -0.87924112]])
# Generate 3x4 array of draws from N(0,1)
= np.random.randn(3, 4)
x x
array([[-0.1602518 , -0.37297688, 0.94243674, -0.19009888],
[ 0.4956038 , -0.14507905, 0.13361256, 1.05479949],
[-2.00509328, 0.22309587, 0.4154616 , -0.74511832]])
# difference across columns, same as diff(x,1) np.diff(x)
array([[-0.21272508, 1.31541362, -1.13253562],
[-0.64068285, 0.27869161, 0.92118693],
[ 2.22818915, 0.19236573, -1.16057992]])
=0) # difference across rows np.diff(x, axis
array([[ 0.6558556 , 0.22789783, -0.80882418, 1.24489837],
[-2.50069708, 0.36817493, 0.28184904, -1.79991781]])
2, axis=0) # Double difference across axis 0 np.diff(x,
array([[-3.15655268, 0.14027709, 1.09067322, -3.04481618]])
2.6 Arrays and matrix functions
Some useful array functions are listed below:
x.view()
: Produces a representation of an array and matrix as another type without copying the data.np.asarray()
: Works similarly tonp.asmatrix
, converting input to an array.np.shape(x)
,x.shape
: Returns the size of each dimension.np.reshape(x)
,x.reshape()
: Gives a new shape to an array without changing its data.np.size()
,x.size
: Returns the total number of elements in the array or matrix.np.ndim()
,x.ndim
: Returns the number of dimensions of the array or matrix.np.tile()
: Replicates an array according to a specified size vector.np.ravel(x)
,x.ravel()
: Returns a flattened view (1-dimensional) of the array or matrix.x.flatten
: Works likeravel
except that it copies the array when producing the flattened version.x.flat
: Poduces anp.flatiter
object (flat iterator) which is an iterator over a flattened view of an array.np.vstack()
,np.hstack()
: Stack arrays vertically or horizontally, respectively.np.concatenate()
: Concatenates arrays along a specified axis.np.split()
,np.vsplit()
,np.hsplit()
: Split arrays vertically or horizontally.np.delete()
: Returns a new array with sub-arrays deleted along a specified axis.np.diag(x)
: Returns the diagonal elements of a squared array as a column vector.np.triu()
,np.tril()
: Return the upper or lower triangular part of an array, respectively.
Some illustrative examples are given below.
= np.arange(5)
x
xtype(x)
array([0, 1, 2, 3, 4])
numpy.ndarray
# Convert x to a matrix
= x.view(type=np.matrix)
y
ytype(y)
matrix([[0, 1, 2, 3, 4]])
numpy.matrix
# Convert y back to an ndarray
= y.view(type=np.ndarray)
z
ztype(z)
array([[0, 1, 2, 3, 4]])
numpy.ndarray
= np.array([[1, 2], [3, 4]])
x x
array([[1, 2],
[3, 4]])
# Convert x to a 4x1 array
= np.reshape(x, (4, 1))
y y
array([[1],
[2],
[3],
[4]])
# Convert y to a 1x4 array
= np.reshape(y, (1, 4)) # return 1 by 4 array
z z
array([[1, 2, 3, 4]])
# Convert z to a 2x2 array
= np.reshape(z, (2, 2))
w w
array([[1, 2],
[3, 4]])
# Total number of elements
= np.random.randn(4, 3)
x # as a function
np.size(x) # as an attribute x.size
12
12
# Number of dimensions
= np.random.randn(4, 3)
x # as a function
np.ndim(x) # as an attribute x.ndim
2
2
# Horizontal stacking
= np.array([[1, 2], [3, 4]])
x
x# Stacks x 3-times horizontally
= np.hstack((x, x, x))
z z
array([[1, 2],
[3, 4]])
array([[1, 2, 1, 2, 1, 2],
[3, 4, 3, 4, 3, 4]])
# Vertical stacking
= np.vstack((z, z)) # stacks z 2-times vertically
y y
array([[1, 2, 1, 2, 1, 2],
[3, 4, 3, 4, 3, 4],
[1, 2, 1, 2, 1, 2],
[3, 4, 3, 4, 3, 4]])
# Vertical splitting
= np.reshape(np.arange(20), (4, 5))
x
x= np.vsplit(x, 2) # vertically split at row 2
y y
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
[array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]]),
array([[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])]
# Delete rows and columns
= np.reshape(np.arange(20), (4, 5))
x
x1, 0) # delete the second row np.delete(x,
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
array([[ 0, 1, 2, 3, 4],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
2, 3], 1) # delete the second and third columns np.delete(x, [
array([[ 0, 1, 4],
[ 5, 6, 9],
[10, 11, 14],
[15, 16, 19]])
# If axis is None, the object is applied to the flattened array.
2, 3]) # flat x and then remove second and third elements np.delete(x, [
array([ 0, 1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19])
# Diagonal elements
= np.array([[1, 2], [3, 4]])
x = np.diag(x) # return diagonal elements
y y
array([1, 4])
# Upper and lower triangular parts
= np.array([[1, 2], [3, 4]])
x # lower triangular part np.tril(x)
array([[1, 0],
[3, 4]])
2.7 Rounding functions
NumPy offers several functions for rounding:
np.around()
: Rounds to the nearest integer (or to a specified number of decimals).np.floor()
: Rounds down to the nearest integer (i.e., the largest integer less than or equal to the input).np.ceil()
: Rounds up to the nearest integer (i.e., the smallest integer greater than or equal to the input).
# Generate a 2x3 array of draws from N(0,1)
= np.random.randn(2, 3)
x x
array([[-0.54933955, -0.91711933, 0.79997799],
[ 1.50453465, -0.71679686, -0.40924795]])
# Round to the nearest integer
np.around(x)
array([[-1., -1., 1.],
[ 2., -1., -0.]])
# Round x to 2 decimals
2) np.around(x,
array([[-0.55, -0.92, 0.8 ],
[ 1.5 , -0.72, -0.41]])
round(2) # using the round method x.
array([[-0.55, -0.92, 0.8 ],
[ 1.5 , -0.72, -0.41]])
# Round down to the nearest integer
np.floor(x)
array([[-1., -1., 0.],
[ 1., -1., -1.]])
# Round up to the nearest integer
np.ceil(x)
array([[-0., -0., 1.],
[ 2., -0., -0.]])
2.8 Sorting and Nan functions
We list some useful NumPy functions related to sorting and handling NaN
values below:
np.sort()
: Sorts the elements of an array.x.sort()
: Performs an in-place sort of the arrayx
.np.argsort()
: Returns the indices that would sort the array.x.max()
/x.min()
: Return the maximum or minimum value in the arrayx
.np.amax()
/np.amin()
: Return the maximum or minimum value in the array.np.argmax()
/np.argmin()
: Return the index of the maximum or minimum element.np.maximum()
/np.minimum()
: Return the maximum/minimum of two arrays.np.nan
: Represents “Not a Number” (NaN
), used for missing or undefined values.np.inf
: Represents positive infinity.np.nansum()
: Returns the sum of array elements, ignoring NaNs.np.nanmax()
,np.nanmin()
: Return the maximum or minimum, ignoring NaNs.np.nanargmax()
,np.nanargmin()
: Return the index of the maximum or minimum, ignoring NaNs.
Some illustrative examples are given below.
# Generate a 4x2 array of draws from N(0,1)
= np.random.randn(4, 2)
x x
array([[ 0.21852789, 2.6070495 ],
[ 0.92769899, -0.29198578],
[-1.4172225 , 1.44619032],
[-0.44457761, -0.10921362]])
# sort across columns np.sort(x)
array([[ 0.21852789, 2.6070495 ],
[-0.29198578, 0.92769899],
[-1.4172225 , 1.44619032],
[-0.44457761, -0.10921362]])
0) # sort across rows np.sort(x,
array([[-1.4172225 , -0.29198578],
[-0.44457761, -0.10921362],
[ 0.21852789, 1.44619032],
[ 0.92769899, 2.6070495 ]])
# Generate 3 draws from N(0,1)
= np.random.randn(3)
x x
array([-0.32983537, 0.67431804, -1.14991394])
# does not change x
np.sort(x) x
array([-1.14991394, -0.32983537, 0.67431804])
array([-0.32983537, 0.67431804, -1.14991394])
= np.random.randn(3, 4)
x x
array([[-0.41121503, -1.30520492, -0.49528635, 0.36963905],
[ 1.07718085, 1.12375138, -1.14729202, 0.72049592],
[-0.95987531, 0.71336491, 0.02871864, -0.57437088]])
# maximum element
np.amax(x) max() # maximum element
x.max(0) # maximum element across rows
x.max(1) # maximum element across columns x.
1.1237513829031516
1.1237513829031516
array([1.07718085, 1.12375138, 0.02871864, 0.72049592])
array([0.36963905, 1.12375138, 0.71336491])
= np.random.randn(4) # generate 4 draws from N(0,1)
x = np.random.randn(4) # generate 4 draws from N(0,1)
y np.maximum(x, y)
array([-0.50666695, 0.83742553, 1.31731035, 0.99110106])
= np.random.randn(5) # generate 4 draws from N(0,1)
x 1] = np.nan
x[3] = None
x[ x
array([ 0.76838131, nan, 0.67401203, nan, -0.63483764])
max(x) # return nan
np.# ignore nan value
np.nanmax(x) sum(x) # return nan
np.# ignore nan value np.nansum(x)
nan
0.768381309306442
nan
0.8075557065828013
2.9 Linear algebra functions
The linear algebra functions are provided in the linalg
module. For more information, see the Linear algebra section from the NumPy documentation. Below, we list some useful linear algebra functions for econometric analysis.
np.linalg.matrix_power(A, n)
: Raises the square matrix A to the integer power n.np.linalg.svd(A)
: Computes the singular value decomposition of matrix A.np.linalg.cond(A)
: Computes the condition number of matrix A.np.linalg.slogdet(A)
: Computes the sign and logarithm of the absolute value of the determinant of a square matrix A.np.linalg.solve(X, y)
: Solves \(X\beta=y\) for \(\beta\) when \(X\) is invertible.np.linalg.lstsq(X, y)
: Returns the least squared solution of \(y=X\beta\).np.linalg.cholesky(A)
: Returns the Cholesky decomposition of A.np.linalg.det(A)
: Returns the determinant of A.np.linalg.eig(A)
: Computes the eigenvalues and eigenvectors of A.np.linalg.inv(A)
: Computes the inverse of A.np.linalg.kron(x,y)
: Computes the kronecker product \(x\otimes y\).np.trace(A)
: Computes the trace of A.np.linalg.matrix_rank(A)
: Computes the rank of A using the SVD method.
Some illustrative examples are given below.
# Solve the equation Xb=y for b
= np.array([[1.0, 2.0, 3.0], [3.0, 3.0, 4.0], [1.0, 1.0, 4.0]])
X = np.array([[1.0], [2.0], [3.0]])
y np.linalg.solve(X, y)
array([[ 0.625],
[-1.125],
[ 0.875]])
# Inverse of X
= np.matrix([[1, 0.5], [0.5, 1]])
X np.linalg.inv(X)
matrix([[ 1.33333333, -0.66666667],
[-0.66666667, 1.33333333]])
# Determinant of X
np.linalg.det(X)
0.75
# Eigenvalues and eigenvectors of M
= np.matrix([[1, 0.5], [0.5, 1]])
M = np.linalg.eig(M)
val, vec # Verify the spectral decomposition
* np.diag(val) * vec.T vec
matrix([[1. , 0.5],
[0.5, 1. ]])
# Rank of X
= np.array([[1, 0.5], [1, 0.5]])
X np.linalg.matrix_rank(X)
1