NumPy Practice

Vectors, Matrices

  • object type
  • dimension
  • size
  • shape
  • data type

In [2]:
my_list = [1,2,3]
import numpy as np
arr = np.array(my_list)
print("Type/Class of this object:",type(arr))
print("Here is the vector\n--------------------\n",arr)


Type/Class of this object: <class 'numpy.ndarray'>
Here is the vector
--------------------
 [1 2 3]

In [4]:
my_mat = [[1,2,3],[4,5,6],[7,8,9]]
mat = np.array(my_mat)
print("Type/Class of this object:",type(mat))
print("Here is the matrix\n----------\n",mat,"\n----------")
print("Dimension of this matrix: ",mat.ndim,sep='') #ndim gives the dimensison, 2 for a matrix, 1 for a vector
print("Size of this matrix: ", mat.size,sep='') #size gives the total number of elements
print("Shape of this matrix: ", mat.shape,sep='') #shape gives the number of elements along each axes (dimension)
print("Data type of this matrix: ", mat.dtype,sep='') #dtype gives the data type contained in the array

my_mat = [[1.1,2,3],[4,5.2,6],[7,8.3,9]]
mat = np.array(my_mat)
print("Data type of the modified matrix: ", mat.dtype,sep='') #dtype gives the data type contained in the array
print("\n\nEven tuples can be converted to ndarrays...")

b = np.array([(1.5,2,3), (4,5,6)])
print("We write b = np.array([(1.5,2,3), (4,5,6)])")
print("Matrix made from tuples, not lists\n---------------------------------------")
print(b)


Type/Class of this object: <class 'numpy.ndarray'>
Here is the matrix
----------
 [[1 2 3]
 [4 5 6]
 [7 8 9]] 
----------
Dimension of this matrix: 2
Size of this matrix: 9
Shape of this matrix: (3, 3)
Data type of this matrix: int32
Data type of the modified matrix: float64


Even tuples can be converted to ndarrays...
We write b = np.array([(1.5,2,3), (4,5,6)])
Matrix made from tuples, not lists
---------------------------------------
[[ 1.5  2.   3. ]
 [ 4.   5.   6. ]]

'arange' and 'linspace'


In [66]:
print("A series of numbers:",np.arange(5,16)) # A series of numbers from low to high


A series of numbers: [ 5  6  7  8  9 10 11 12 13 14 15]

In [63]:
print("Numbers spaced apart by 2:",np.arange(0,11,2)) # Numbers spaced apart by 2


Numbers spaced apart by 2: [ 0  2  4  6  8 10]

In [97]:
print("Numbers spaced apart by float:",np.arange(0,11,2.5)) # Numbers spaced apart by 2.5


Numbers spaced apart by float: [  0.    2.5   5.    7.5  10. ]

In [71]:
print("Every 5th number from 50 in reverse order\n",np.arange(50,-1,-5))


Every 5th number from 50 in reverse order
 [50 45 40 35 30 25 20 15 10  5  0]

In [73]:
print("21 linearly spaced numbers between 1 and 5\n--------------------------------------------")
print(np.linspace(1,5,21))


21 linearly spaced numbers between 1 and 5
--------------------------------------------
[ 1.   1.2  1.4  1.6  1.8  2.   2.2  2.4  2.6  2.8  3.   3.2  3.4  3.6  3.8
  4.   4.2  4.4  4.6  4.8  5. ]

Zeroes, Ones, empty, and Identity matrix


In [75]:
print("Vector of zeroes\n---------------------")
print(np.zeros(5))
print("Matrix of zeroes\n--------------------")
print(np.zeros((3,4))) # Notice Tuples


Vector of zeroes
---------------------
[ 0.  0.  0.  0.  0.]
Matrix of zeroes
--------------------
[[ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]]

In [79]:
print("Vector of ones\n---------------------")
print(np.ones(5))
print("Matrix of ones\n---------------------")
print(np.ones((5,2))) # Note matrix dimension specified by Tuples
print("Matrix of 5's\n---------------------")
print(5*np.ones((3,5)))


Vector of ones
---------------------
[ 1.  1.  1.  1.  1.]

Matrix of ones
---------------------
[[ 1.  1.]
 [ 1.  1.]
 [ 1.  1.]
 [ 1.  1.]
 [ 1.  1.]]

Matrix of 5's
---------------------
[[ 5.  5.  5.  5.  5.]
 [ 5.  5.  5.  5.  5.]
 [ 5.  5.  5.  5.  5.]]

In [95]:
print("Empty matrix\n-------------\n", np.empty((3,5)))


Empty matrix
-------------
 [[ 0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.]]

In [43]:
mat1 = np.eye(4) 
print("Identity matrix of dimension", mat1.shape)
print(mat1)


Identity matrix of dimension (4, 4)
[[ 1.  0.  0.  0.]
 [ 0.  1.  0.  0.]
 [ 0.  0.  1.  0.]
 [ 0.  0.  0.  1.]]

Random number generation


In [44]:
print("Random number generation (from Uniform distribution)")
print(np.random.rand(2,3)) # 2 by 3 matrix with random numbers ranging from 0 to 1, Note no Tuple is necessary


Random number generation (from Uniform distribution)
[[ 0.1693859   0.29321079  0.2806974 ]
 [ 0.88785322  0.53001756  0.84104681]]

In [51]:
print("Numbers from Normal distribution with zero mean and standard deviation 1 i.e. standard normal")
print(np.random.randn(4,3))


Numbers from Normal distribution with zero mean and standard deviation 1 i.e. standard normal
[[ 0.76079984 -0.08297581 -0.73919191]
 [ 1.28987052  1.56506408 -0.61674267]
 [-1.18697333 -1.68918981  1.06159956]
 [ 0.79886215 -1.14500189 -0.74527344]]

In [49]:
print("Random integers...")
print(np.random.randint(1,100,10)) #randint (low, high, # of samples to be drawn)
print("20 samples drawn from a dice throw:",np.random.randint(1,7,20)) # 20 samples drawn from a dice throw


Random integers...
[98  2 43 71 37 30 30  7 53 71]
20 samples drawn from a dice throw: [1 4 3 2 3 5 6 6 5 4 4 4 3 5 3 3 4 5 5 1]

Reshaping, min, max, sort


In [5]:
from numpy.random import randint as ri
a = ri(1,100,30)
b = a.reshape(2,3,5)
c = a.reshape(6,5)
print ("Shape of a:", a.shape)
print ("Shape of b:", b.shape)
print ("Shape of c:", c.shape)
print("\nb looks like\n",'-'*20,"\n",b,"\n",'-'*20)
print("\nc looks like\n",'-'*20,"\n",c,"\n",'-'*20)

A = ri(1,100,10) # Vector of random interegrs
print("\nVector of random integers\n",'-'*50,"\n",A)
print("\nHere is the sorted vector\n",'-'*50,"\n",np.sort(A, kind='mergesort'))

M = ri(1,100,25).reshape(5,5) # Matrix of random interegrs
print("\n5x5 Matrix of random integers\n",'-'*50,"\n",M)
print("\nHere is the sorted matrix along each row\n",'-'*50,"\n",np.sort(M, kind='mergesort'))
print("\nHere is the sorted matrix along each column\n",'-'*50,"\n",np.sort(M, axis=0, kind='mergesort'))


Shape of a: (30,)
Shape of b: (2, 3, 5)
Shape of c: (6, 5)

b looks like
 -------------------- 
 [[[57 40 21 94 88]
  [30 70 16 78 91]
  [ 5 27 17 39 95]]

 [[33 30 49 25 16]
  [14 86  9 89 41]
  [85 38 35 57 75]]] 
 --------------------

c looks like
 -------------------- 
 [[57 40 21 94 88]
 [30 70 16 78 91]
 [ 5 27 17 39 95]
 [33 30 49 25 16]
 [14 86  9 89 41]
 [85 38 35 57 75]] 
 --------------------

Vector of random integers
 -------------------------------------------------- 
 [71 39 22 75 21  8 81 36 70 62]

Here is the sorted vector
 -------------------------------------------------- 
 [ 8 21 22 36 39 62 70 71 75 81]

5x5 Matrix of random integers
 -------------------------------------------------- 
 [[40 93 36 16  5]
 [86 27 77 43 49]
 [93  9 29 75 64]
 [96 24 78 46 27]
 [ 6 80 73 34 47]]

Here is the sorted matrix along each row
 -------------------------------------------------- 
 [[ 5 16 36 40 93]
 [27 43 49 77 86]
 [ 9 29 64 75 93]
 [24 27 46 78 96]
 [ 6 34 47 73 80]]

Here is the sorted matrix along each column
 -------------------------------------------------- 
 [[ 6  9 29 16  5]
 [40 24 36 34 27]
 [86 27 73 43 47]
 [93 80 77 46 49]
 [96 93 78 75 64]]

In [6]:
print("Max of a:", a.max())
print("Max of b:", b.max())
print("Max of a location:", a.argmax())
print("Max of b location:", b.argmax())
print("Max of c location:", b.argmax())


Max of a: 96
Max of b: 96
Max of a location: 21
Max of b location: 21
Max of c location: 21

Indexing and slicing


In [6]:
arr = np.arange(0,11)
print("Array:",arr)
print("Element at 7th index is:", arr[7])
print("Elements from 3rd to 5th index are:", arr[3:6])
print("Elements up to 4th index are:", arr[:4])
print("Elements from last backwards are:", arr[-1::-1])
print("3 Elements from last backwards are:", arr[-1:-6:-2])

arr = np.arange(0,21,2)
print("New array:",arr)
print("Elements at 2nd, 4th, and 9th index are:", arr[[2,4,9]]) # Pass a list as a index to subset


Array: [ 0  1  2  3  4  5  6  7  8  9 10]
Element at 7th index is: 7
Elements from 3rd to 5th index are: [3 4 5]
Elements up to 4th index are: [0 1 2 3]
Elements from last backwards are: [10  9  8  7  6  5  4  3  2  1  0]
3 Elements from last backwards are: [10  8  6]
New array: [ 0  2  4  6  8 10 12 14 16 18 20]
Elements at 2nd, 4th, and 9th index are: [ 4  8 18]

In [7]:
mat = np.array(ri(10,100,15)).reshape(3,5)
print("Matrix of random 2-digit numbers\n--------------------------------\n",mat)

print("\nDouble bracket indexing\n------------------------")
print("Element in row index 1 and column index 2:", mat[1][2])

print("\nSingle bracket with comma indexing\n----------------------------------")
print("Element in row index 1 and column index 2:", mat[1,2])
print("\nRow or column extract\n----------------------")

print("Entire row at index 2:", mat[2])
print("Entire column at index 3:", mat[:,3])

print("\nSubsetting sub-matrices\n--------------------------")
print("Matrix with row indices 1 and 2 and column indices 3 and 4\n", mat[1:3,3:5])
print("Matrix with row indices 0 and 1 and column indices 1 and 3\n", mat[0:2,[1,3]])


Matrix of random 2-digit numbers
--------------------------------
 [[10 88 51 68 71]
 [47 76 62 38 67]
 [71 43 44 55 31]]

Double bracket indexing
------------------------
Element in row index 1 and column index 2: 62

Single bracket with comma indexing
----------------------------------
Element in row index 1 and column index 2: 62

Row or column extract
----------------------
Entire row at index 2: [71 43 44 55 31]
Entire column at index 3: [68 38 55]

Subsetting sub-matrices
--------------------------
Matrix with row indices 1 and 2 and column indices 3 and 4
 [[38 67]
 [55 31]]
Matrix with row indices 0 and 1 and column indices 1 and 3
 [[88 68]
 [76 38]]

Conditional subsetting


In [9]:
mat = np.array(ri(10,100,15)).reshape(3,5)
print("Matrix of random 2-digit numbers\n--------------------------------\n",mat)
print ("Elements greater than 50\n", mat[mat>50])


Matrix of random 2-digit numbers
--------------------------------
 [[76 74 57 40 23]
 [11 39 74 33 38]
 [56 32 38 43 23]]
Elements greater than 50
 [76 74 57 74 56]

Array operations (array-array, array-scalar, universal functions)


In [8]:
mat1 = np.array(ri(1,10,9)).reshape(3,3)
mat2 = np.array(ri(1,10,9)).reshape(3,3)
print("\n1st Matrix of random single-digit numbers\n----------------------------------------\n",mat1)
print("\n2nd Matrix of random single-digit numbers\n----------------------------------------\n",mat2)

print("\nAddition\n------------------\n", mat1+mat2)
print("\nMultiplication\n------------------\n", mat1*mat2)
print("\nDivision\n------------------\n", mat1/mat2)
print("\nLineaer combination: 3*A - 2*B\n-----------------------------\n", 3*mat1-2*mat2)

print("\nAddition of a scalar (100)\n-------------------------\n", 100+mat1)

print("\nExponentiation, matrix cubed here\n----------------------------------------\n", mat1**3)
print("\nExponentiation, sq-root using pow function\n-------------------------------------------\n",pow(mat1,0.5))


1st Matrix of random single-digit numbers
----------------------------------------
 [[4 1 3]
 [2 4 3]
 [4 1 6]]

2nd Matrix of random single-digit numbers
----------------------------------------
 [[6 1 2]
 [7 2 5]
 [2 6 1]]

Addition
------------------
 [[10  2  5]
 [ 9  6  8]
 [ 6  7  7]]

Multiplication
------------------
 [[24  1  6]
 [14  8 15]
 [ 8  6  6]]

Division
------------------
 [[ 0.66666667  1.          1.5       ]
 [ 0.28571429  2.          0.6       ]
 [ 2.          0.16666667  6.        ]]

Lineaer combination: 3*A - 2*B
-----------------------------
 [[ 0  1  5]
 [-8  8 -1]
 [ 8 -9 16]]

Addition of a scalar (100)
-------------------------
 [[104 101 103]
 [102 104 103]
 [104 101 106]]

Exponentiation, matrix cubed here
----------------------------------------
 [[ 64   1  27]
 [  8  64  27]
 [ 64   1 216]]

Exponentiation, sq-root using pow function
-------------------------------------------
 [[ 2.          1.          1.73205081]
 [ 1.41421356  2.          1.73205081]
 [ 2.          1.          2.44948974]]

NumPy mathematical functions on array


In [12]:
mat1 = np.array(ri(1,10,9)).reshape(3,3)
mat2 = np.array(ri(1,10,9)).reshape(3,3)
print("\n1st Matrix of random single-digit numbers\n----------------------------------------\n",mat1)
print("\n2nd Matrix of random single-digit numbers\n----------------------------------------\n",mat2)

print("\nSq-root of 1st matrix using np\n------------------\n", np.sqrt(mat1))
print("\nExponential power of 1st matrix using np\n",'-'*50,"\n", np.exp(mat1))
print("\n10-base logarithm on 1st matrix using np\n",'-'*50,"\n", np.log10(mat1))
print("\nModulo reminder using np\n",'-'*50,"\n", np.fmod(mat1,mat2))

print("\nCombination of functions by shwoing exponetial decay of a sine wave\n",'-'*70)
A = np.linspace(0,12*np.pi,1001)
import matplotlib.pyplot as plt
plt.scatter(x=A,y=100*np.exp(-A/10)*(np.sin(A)))
plt.title("Exponential decay of sine wave: exp(-x)*sin(x)")
plt.show()


1st Matrix of random single-digit numbers
----------------------------------------
 [[2 5 2]
 [1 1 3]
 [5 6 1]]

2nd Matrix of random single-digit numbers
----------------------------------------
 [[6 9 3]
 [2 6 6]
 [3 9 3]]

Sq-root of 1st matrix using np
------------------
 [[ 1.41421356  2.23606798  1.41421356]
 [ 1.          1.          1.73205081]
 [ 2.23606798  2.44948974  1.        ]]

Exponential power of 1st matrix using np
 -------------------------------------------------- 
 [[   7.3890561   148.4131591     7.3890561 ]
 [   2.71828183    2.71828183   20.08553692]
 [ 148.4131591   403.42879349    2.71828183]]

10-base logarithm on 1st matrix using np
 -------------------------------------------------- 
 [[ 0.30103     0.69897     0.30103   ]
 [ 0.          0.          0.47712125]
 [ 0.69897     0.77815125  0.        ]]

Modulo reminder using np
 -------------------------------------------------- 
 [[2 5 2]
 [1 1 3]
 [2 6 1]]

Combination of functions by shwoing exponetial decay of a sine wave
 ----------------------------------------------------------------------

NumPy basic statistics on array


In [54]:
mat1 = np.array(ri(1,10,9)).reshape(3,3)
mat2 = np.array(ri(1,10,9)).reshape(3,3)
print("\n1st Matrix of random single-digit numbers\n","-"*50,"\n",mat1)
print("\n2nd Matrix of random single-digit numbers\n","-"*50,"\n",mat2)

print("\nSum of all numbers in 1st matrix\n","-"*50,"\n",np.sum(mat1))
print("\nSum of all numbers in columns of 1st matrix\n","-"*50,"\n",np.sum(mat1,axis=0))
print("\nSum of all numbers in rows of 1st matrix\n","-"*50,"\n",np.sum(mat1,axis=1))
print("\nMean of all numbers in 1st matrix\n","-"*50,"\n",np.mean(mat1))
print("\nStandard deviation of all numbers in 1st matrix\n","-"*50,"\n",np.std(mat1))

mat1 = np.array(ri(1,100,9)).reshape(3,3)
print("\nModified matrix of random numbers from 1 to 99\n","-"*50,"\n",mat1)
print("\nStandard deviation of all numbers in the modified matrix, a larger number\n","-"*80,"\n",np.std(mat1))
print("\nVariance of all numbers in the modified matrix, a larger number\n","-"*80,"\n",np.var(mat1))
print("\nMedian of all numbers in the modified matrix\n","-"*60,"\n",np.median(mat1))

mat2 = np.array(ri(1,100,50)).reshape(10,5)
print("\nModified matrix of 50 random numbers from 1 to 99\n","-"*50,"\n",mat2)
print("\nStandard deviation along the columns in the modified matrix\n","-"*60,"\n",np.std(mat2,axis=0))

mat1 = np.array(ri(1,100,20)).reshape(4,5)
print("\nModified matrix of random numbers from 1 to 49\n","-"*50,"\n",mat1)
print("\nFlattened and sorted matrix (as vector)\n","-"*50,"\n",np.sort(mat1.reshape(1,20)))
print("\n50th percentile of all numbers in the modified matrix\n","-"*60,"\n",np.percentile(mat1,50))
print("\n90th percentile of all numbers in the modified matrix\n","-"*60,"\n",np.percentile(mat1,90))


1st Matrix of random single-digit numbers
 -------------------------------------------------- 
 [[9 9 8]
 [5 9 3]
 [6 5 3]]

2nd Matrix of random single-digit numbers
 -------------------------------------------------- 
 [[4 4 7]
 [1 4 2]
 [3 6 7]]

Sum of all numbers in 1st matrix
 -------------------------------------------------- 
 57

Sum of all numbers in columns of 1st matrix
 -------------------------------------------------- 
 [20 23 14]

Sum of all numbers in rows of 1st matrix
 -------------------------------------------------- 
 [26 17 14]

Mean of all numbers in 1st matrix
 -------------------------------------------------- 
 6.33333333333

Standard deviation of all numbers in 1st matrix
 -------------------------------------------------- 
 2.35702260396

Modified matrix of random numbers from 1 to 99
 -------------------------------------------------- 
 [[26 82 58]
 [34  4 65]
 [99 31 75]]

Standard deviation of all numbers in the modified matrix, a larger number
 -------------------------------------------------------------------------------- 
 29.0287214094

Variance of all numbers in the modified matrix, a larger number
 -------------------------------------------------------------------------------- 
 842.666666667

Median of all numbers in the modified matrix
 ------------------------------------------------------------ 
 58.0

Modified matrix of 50 random numbers from 1 to 99
 -------------------------------------------------- 
 [[83 39 19 67 86]
 [29 76 87 88 29]
 [29 40 35  5 38]
 [42 76 57 87 80]
 [68 46 59 69 46]
 [27 83 39 27 43]
 [25 50 35 16 80]
 [36  7 53 42 51]
 [ 7 34 98 90 76]
 [93 48 12 61 90]]

Standard deviation along the columns in the modified matrix
 ------------------------------------------------------------ 
 [ 26.52338591  21.87898535  26.04688081  29.47473494  21.46369027]

Modified matrix of random numbers from 1 to 49
 -------------------------------------------------- 
 [[39 57  8  5 96]
 [ 1 54 93 82 96]
 [27 41 32 10 86]
 [90 61 33 91 27]]

Flattened and sorted matrix (as vector)
 -------------------------------------------------- 
 [[ 1  5  8 10 27 27 32 33 39 41 54 57 61 82 86 90 91 93 96 96]]

50th percentile of all numbers in the modified matrix
 ------------------------------------------------------------ 
 47.5

90th percentile of all numbers in the modified matrix
 ------------------------------------------------------------ 
 93.3

Correlation and covariance


In [13]:
A = ri(1,5,20) # 20 random integeres from a small range (1-10)
B = 2*A+5*np.random.randn(20) # B is twice that of A plus some random noise
print("\nB is twice that of A plus some random noise")
plt.scatter(A,B) # Scatter plot of B
plt.title("Scatter plot of A vs. B, expect a small positive correlation")
plt.show()
print(np.corrcoef(A,B)) # Correleation coefficient matrix between A and B

A = ri(1,50,20) # 20 random integeres from a larger range (1-50)
B = 100-2*A+10*np.random.randn(20) # B is 100 minus twice that of A plus some random noise
print("\nB is 100 minus twice that of A plus some random noise")
plt.scatter(A,B) # Scatter plot of B
plt.title("Scatter plot of A vs. B, expect a large negative correlation")
plt.show()
print("")
print(np.corrcoef(A,B)) # Correleation coefficient matrix between A and B


B is twice that of A plus some random noise
[[ 1.          0.57920259]
 [ 0.57920259  1.        ]]

B is 100 minus twice that of A plus some random noise
[[ 1.       -0.899854]
 [-0.899854  1.      ]]

Some matrix/vector operations

Dot/Inner/Outer products


In [46]:
A = np.arange(1,10).reshape(3,3)
B = ri(1,10,9).reshape(3,3)
print("\n1st Matrix of 1-9 single-digit numbers (A)\n","-"*50,"\n",A)
print("\n2nd Matrix of random single-digit numbers (B)\n","-"*50,"\n",B)

print("\nDot product of A and B \n","-"*50,"\n",np.dot(A,B))

A = np.arange(1,6)
B = ri(1,10,5)
print("\n1st Vector of 1-5 numbers (A)\n","-"*50,"\n",A)
print("\n2nd Vector of 5 random single-digit numbers (B)\n","-"*50,"\n",B)

print("\nInner product of vectors A and B \n","-"*50,"\n",np.inner(A,B), "(sum of all pairwise elements)")
print("\nOuter product of vectors A and B \n","-"*50,"\n",np.outer(A,B))


1st Matrix of 1-9 single-digit numbers (A)
 -------------------------------------------------- 
 [[1 2 3]
 [4 5 6]
 [7 8 9]]

2nd Matrix of random single-digit numbers (B)
 -------------------------------------------------- 
 [[2 9 8]
 [7 4 7]
 [2 7 9]]

Dot product of A and B 
 -------------------------------------------------- 
 [[ 22  38  49]
 [ 55  98 121]
 [ 88 158 193]]

1st Vector of 1-5 numbers (A)
 -------------------------------------------------- 
 [1 2 3 4 5]

2nd Vector of 5 random single-digit numbers (B)
 -------------------------------------------------- 
 [5 8 7 8 6]

Inner product of vectors A and B 
 -------------------------------------------------- 
 104 (sum of all pairwise elements)

Outer product of vectors A and B 
 -------------------------------------------------- 
 [[ 5  8  7  8  6]
 [10 16 14 16 12]
 [15 24 21 24 18]
 [20 32 28 32 24]
 [25 40 35 40 30]]

Transpose


In [56]:
A = ri(1,10,9).reshape(3,3)
print("\n3x3 Matrix of random single-digit numbers\n","-"*50,"\n",A)
print("\nMatrix transpose\n","-"*50,"\n",np.transpose(A))

B = ri(1,10,6).reshape(3,2)
print("\n3x2 Matrix of random single-digit numbers\n","-"*50,"\n",B)
print("\n2x3 Matrix transpose\n","-"*50,"\n",np.transpose(B))
print("\nMatrix multiplication of B and B-transpose\n","-"*50,"\n",np.dot(B, np.transpose(B)))


3x3 Matrix of random single-digit numbers
 -------------------------------------------------- 
 [[5 8 8]
 [9 1 2]
 [4 8 5]]

Matrix transpose
 -------------------------------------------------- 
 [[5 9 4]
 [8 1 8]
 [8 2 5]]

3x2 Matrix of random single-digit numbers
 -------------------------------------------------- 
 [[7 4]
 [1 3]
 [6 3]]

2x3 Matrix transpose
 -------------------------------------------------- 
 [[7 1 6]
 [4 3 3]]

Matrix multiplication of B and B-transpose
 -------------------------------------------------- 
 [[65 19 54]
 [19 10 15]
 [54 15 45]]

Trace


In [59]:
A = ri(1,10,16).reshape(4,4)
print("\n4x4 Matrix of random single-digit numbers\n","-"*50,"\n",A)
print("\nMatrix trace\n","-"*50,"\n",np.trace(A))
print("\nMatrix trace with ofset +1 (upper triangle)\n","-"*50,"\n",np.trace(A,offset=1))
print("\nMatrix trace with ofset -1 (lower triangle)\n","-"*50,"\n",np.trace(A,offset=-1))


4x4 Matrix of random single-digit numbers
 -------------------------------------------------- 
 [[8 5 5 5]
 [4 5 9 3]
 [3 6 9 3]
 [1 4 5 6]]

Matrix trace
 -------------------------------------------------- 
 28

Matrix trace with ofset +1 (upper triangle)
 -------------------------------------------------- 
 17

Matrix trace with ofset -1 (lower triangle)
 -------------------------------------------------- 
 15