0% found this document useful (0 votes)
3 views

Python_Numpy

Uploaded by

NGÔ THẾ ANH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python_Numpy

Uploaded by

NGÔ THẾ ANH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Numeric Computing with Numpy

Thu Huong Nguyen1 and Si Thin Nguyen2


1
[email protected]
2
[email protected]
1,2
Faculty of Computer Science, VKU

1 Exercises with solutions


1.1 Introduction
1.1.1 Import the numpy package under the name np

[ ]: import numpy as np

1.1.2 Print the numpy version and the configuration

[ ]: import numpy as np
print(np.__version__)
print(np.show_config())

1.22.4
openblas64__info:
libraries = ['openblas64_', 'openblas64_']
library_dirs = ['/opt/arm64-builds/lib']
language = c
define_macros = [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'),
('HAVE_BLAS_ILP64', None)]
runtime_library_dirs = ['/opt/arm64-builds/lib']
blas_ilp64_opt_info:
libraries = ['openblas64_', 'openblas64_']
library_dirs = ['/opt/arm64-builds/lib']
language = c
define_macros = [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'),
('HAVE_BLAS_ILP64', None)]
runtime_library_dirs = ['/opt/arm64-builds/lib']
openblas64__lapack_info:
libraries = ['openblas64_', 'openblas64_']
library_dirs = ['/opt/arm64-builds/lib']
language = c
define_macros = [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'),

1
('HAVE_BLAS_ILP64', None), ('HAVE_LAPACKE', None)]
runtime_library_dirs = ['/opt/arm64-builds/lib']
lapack_ilp64_opt_info:
libraries = ['openblas64_', 'openblas64_']
library_dirs = ['/opt/arm64-builds/lib']
language = c
define_macros = [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'),
('HAVE_BLAS_ILP64', None), ('HAVE_LAPACKE', None)]
runtime_library_dirs = ['/opt/arm64-builds/lib']
Supported SIMD extensions in this NumPy install:
baseline = NEON,NEON_FP16,NEON_VFPV4,ASIMD
found = ASIMDHP
not found = ASIMDDP
None

1.2 Numpy array/Vector/Matrix creation


1.2.1 Write a program to create a Numpy array
1. one-dimensional
2. two-dimensional
Hint: Use np.array()

[ ]: # one-dimensional array
one_arr = np.array([1, 2, 3, 4, 5])
print("One-dimensional NumPy array: ",one_arr)
l = [1, 2, 3, 4]
print("Original List:",l)
list_arr = np.array(l)
print("One-dimensional NumPy array from a given numeric list: ",list_arr)
# two-dimensional array
two_arr=arr = np.array([[1, 2, 3], [4, 5, 6]])
# from a list of lists
listOfLists = [[1, 2, 3], [4, 5, 6], [7,8,9]]
print("Original list of lists: ",listOfLists)
list2_arr = np.array(listOfLists)
print("Two-dimensional NumPy array from list of two lists : \n",list2_arr)

One-dimensional NumPy array: [1 2 3 4 5]


Original List: [1, 2, 3, 4]
One-dimensional NumPy array from a given numeric list: [1 2 3 4]
Original list of lists 1: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Two-dimensional NumPy array from list of two lists :
[[1 2 3]
[4 5 6]
[7 8 9]]

2
1.2.2 Write a program to convert a list and tuple into Numpy arrays
Hint: Use the function asarray()

[ ]: my_list = [1, 2, 3, 4, 5, 6, 7, 8]
print("List to array: ")
print(np.asarray(my_list))
my_tuple = ([8, 4, 6], [1, 2, 3])
print("Tuple to array: ")
print(np.asarray(my_tuple))

List to array:
[1 2 3 4 5 6 7 8]
Tuple to array:
[[8 4 6]
[1 2 3]]

1.2.3 Write a program to create a 2d Numpy array as below:


[[1. 1. 1. 1. 1.]
[1. 0. 0. 0. 1.]
[1. 0. 0. 0. 1.]
[1. 0. 0. 0. 1.]
[1. 1. 1. 1. 1.]]

[ ]: x = np.ones((5,5))
print("Original array:")
print(x)
print("Output array with 1 on the border and 0 inside in the array")
x[1:-1,1:-1] = 0
print(x)

Original array:
[[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]]
Output array with 1 on the border and 0 inside in the array
[[1. 1. 1. 1. 1.]
[1. 0. 0. 0. 1.]
[1. 0. 0. 0. 1.]
[1. 0. 0. 0. 1.]
[1. 1. 1. 1. 1.]]

3
1.2.4 Write a program to create a 3x3 matrix with values ranging from 1 to 9

[ ]: x = np.arange(1, 10).reshape(3,3)
print(x)

[[1 2 3]
[4 5 6]
[7 8 9]]

1.2.5 Write a program to create a 8x8 matrix and fill it with a checkerboard pattern
filled with 0 and 1.
[ ]: print("Checkerboard pattern:")
x = np.zeros((8,8),dtype=int)
x[1::2,::2] = 1
x[::2,1::2] = 1
print(x)

Checkerboard pattern:
[[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]]

1.2.6 Write a program to create a 8x8 matrix and fill it with a checkerboard pattern
filled with 0 and 1 using the function tile ()

[ ]: print("Checkerboard pattern:")
x = np.tile( np.array([[0,1],[1,0]]), (4,4))
print(x)

Checkerboard pattern:
[[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]]

4
1.2.7 Write a program to create a null vector of size 10 and update sixth value to 11.

[ ]: x = np.zeros(10)
print(x)
print("Update sixth value to 11")
x[6] = 11
print(x)

[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
Update sixth value to 11
[ 0. 0. 0. 0. 0. 0. 11. 0. 0. 0.]

1.2.8 Write a NumPy program to create an empty and a full array.

[ ]: # Create an empty array


x = np.empty((5,7))
print(x)
# Create a full array
y = np.full((4,3),9)
print(y)

[[-3.10503618e+231 -3.10503618e+231 2.17053206e-314 4.44659081e-323


5.92878775e-323 7.76593822e-299 4.50155003e-294]
[-8.91494661e+303 nan -1.17273833e-308 2.19702506e-314
2.19702506e-314 2.47032823e-323 2.16412116e-314]
[ 2.16412116e-314 3.45845952e-323 2.16412120e-314 2.16412120e-314
8.60974374e-129 2.19706806e-314 2.19706806e-314]
[ 1.97626258e-323 2.16412115e-314 2.16412115e-314 1.48219694e-323
2.16412113e-314 2.16412113e-314 4.44659081e-323]
[ 2.16412123e-314 2.16412123e-314 -1.88173352e+121 2.19706813e-314
2.19706813e-314 1.99335786e+197 2.19528522e-314]]
[[9 9 9]
[9 9 9]
[9 9 9]
[9 9 9]]

1.2.9 Write a NumPy program to create a 3-D array with ones on a diagonal and
zeros elsewhere.
[ ]: import numpy as np
x = np.eye(3)
print(x)

[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]

5
1.3 Subsetting/Slicing/Indexing
1.3.1 Create an arrary as follows:
• Return the array of elements in the 2nd row
• Return the array of elements in the third column
• Return a sub-array consisting of the odd rows and even columns of.

[ ]: import numpy
Y = numpy.array([
[3,6,9,12],
[15,18,21,24],
[27,30,33,36],
[39,42,45,48],
[51,54,57,60]
])
Y[::2, 1::2]

[ ]: array([[ 6, 12],
[30, 36],
[54, 60]])

1.3.2 Extract from the array np.array([3,4,6,10,24,89,45,43,46,99,100]) with Boolean


masking all the number
• which are not divisible by 3
• which are divisible by 5
• which are divisible by 3 and 5
• which are divisible by 3 and set them to 42

[ ]: import numpy as np
A = np.array([3,4,6,10,24,89,45,43,46,99,100])
div3 = A[A%3!=0]
print("Elements of A not divisible by 3:")
print(div3)
div5 = A[A%5==0]
print("Elements of A divisible by 5:")
print(div5)
print("Elements of A, which are divisible by 3 and 5:")
print(A[(A%3==0) & (A%5==0)])
print("------------------")
A[A%3==0] = 42
print("""New values of A after setting the elements of A,
which are divisible by 3, to 42:""")
print(A)

Elements of A not divisible by 3:


[ 4 10 89 43 46 100]
Elements of A divisible by 5:
[ 10 45 100]

6
Elements of A, which are divisible by 3 and 5:
[45]
------------------
New values of A after setting the elements of A,
which are divisible by 3, to 42:
[ 42 4 42 10 42 89 42 43 46 42 100]

1.4 Broadcasting
1.4.1 Write a NumPy program to broadcast on different shapes of arrays where p(3,3)
+ q(3). The p variable has a shape of (3, 3), while q only has a shape of 3.

[ ]: import numpy as np
p = np.array([[0, 0, 0],
[1, 2, 3],
[4, 5, 6]])
q= np.array([10, 11, 12])
print("Original arrays:")
print("Array-1")
print(p)
print("Array-2")
print(q)
print("\nNew Array:")
new_array1 = p + q
print(new_array1)

1.4.2 Selling pies on weekends. Sell 3 types of pies at different prices, and the following
number of each pie was sold last weekend. How much money I made per pie
type per day? Requirement: Don’t use loops

[]: cost = np.array([20, 15, 25])


print("Pie cost:")
print(cost)
sales = np.array([[2, 3, 1], [6, 3, 3], [5, 3, 5]])

7
print("\nPie sales (#):")
print(sales)

Pie cost:
[20 15 25]

Pie sales (#):


[[2 3 1]
[6 3 3]
[5 3 5]]
we could make them the same size, and multiply corresponding elements “elementwise”:

[]: cost = np.repeat(cost, 3).reshape((3, 3))


cost

[]: array([[20, 20, 20],


[15, 15, 15],
[25, 25, 25]])

[]: cost * sales

[]: array([[ 40, 60, 20],


[ 90, 45, 45],
[125, 75, 125]])

or

[]: cost = np.array([20, 15, 25]).reshape(3, 1)


print(f" cost shape: {cost.shape}")

cost shape: (3, 1)

[]: cost * sales

8
[]: array([[ 40, 60, 20],
[ 90, 45, 45],
[125, 75, 125]])

1.5 Numpy Array Attributes


1.5.1 Find the number of dimensions, shape, the number of elements and the memory
size of each element of a given array.
Example:
Original array:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
Number of array dimensions: 2
Array dimensions:(3, 4)
Number of items: 12
Memory size of each element of the said array: 8
Hints: Use the ndim, shape, size and item size properties respectively.

1.6 Operations on Numpy Array


1.6.1 Write a program to reverse a NumPy array

[ ]: x = np.arange(1, 10)
print("Original array:")
print(x)
print("Reverse array:")
x = x[::-1]
print(x)

Original array:
[1 2 3 4 5 6 7 8 9]
Reverse array:
[9 8 7 6 5 4 3 2 1]

1.6.2 Write a program to convert an Numpy array to a float type

[ ]: x = np.arange(1, 10)
print("Original array")
print(x)
x = np.asfarray(x)
print("Array converted to a float type:")
print(x)

9
Original array
[1 2 3 4 5 6 7 8 9]
Array converted to a float type:
[1. 2. 3. 4. 5. 6. 7. 8. 9.]

1.6.3 Write a program to test whether each element of a 1-D array is also present in
a second array
Example: Array1: [ 0, 1, 2, 3, 5] and Array2: [0, 2, 4]
Compare each element of Array1 and Array2: [ True False False True False]
Hint: Use the function in1d()

[ ]: array1 = np.array([0, 1, 2, 3, 5])


print("Array1: ",array1)
array2 = [0,2,4]
print("Array2: ",array2)
print("Compare each element of array1 and array2")
print(np.in1d(array1, array2))

Array1: [0 1 2 3 5]
Array2: [0, 2, 4]
Compare each element of array1 and array2
[ True False True False False]

1.6.4 Write a program to find common values between two Numpy arrays.
Example: Array1: [ 0 10 20 40 60] and Array2: [10, 30, 40]
Common values between two arrays:[10 40]
Hint: Use the function intersec1d()

[ ]: array1 = np.array([0, 10, 20, 40, 60])


print("Array1: ",array1)
array2 = [10, 30, 40]
print("Array2: ",array2)
print("Common values between two arrays:")
print(np.intersect1d(array1, array2))

Array1: [ 0 10 20 40 60]
Array2: [10, 30, 40]
Common values between two arrays:
[10 40]

1.6.5 Perform the following operations on two arrays:


• substract
• mutiple
• divide
• power

10
• mod
• remainder

[]: import numpy as np


arr=np.array([[0,1,2],[3,4,5],[6,7,8]])
arr1=[10,10,10]
# Substracting the two arrays
arr21 = np.subtract(arr, arr1)
print("Substracting the two arrays:")
print(arr21)
# Multiplying the two arrays
arr22 = np.multiply(arr, arr1)
print("Multiplying the two arrays:")
print(arr22)
# Dividing the two arrays
arr23 = np.divide(arr, arr1)
print("Dividing the two arrays:")
print(arr23)
#Use numpy.power() to calculating exponents of an array of numbers
arr = np.array([5, 3, 6, 9, 2, 4])
arr24 = np.power(arr,3)
print("calculating exponents of an array of numbers:")
print(arr24)
# Use numpy.reciprocal() function
arr = np.array([50, 1.34, 3, 1, 25])
arr26 = np.reciprocal(arr)
print("Use numpy.reciprocal() function")
print(arr26)
# Use reciprocal function
arr = np.array([75], dtype = int)
arr27 = np.reciprocal(arr)
print("Use numpy.reciprocal() function")
print(arr27)
# Use numpy.mod() function
arr = np.array([7,16, 25])
arr1 = np.array([4,8,6])
arr28 = np.mod(arr,arr1)
print("Use numpy.mod() function")
print(arr28)
# Use numpy.remainder() function
arr = np.array([7,16, 25])
arr1 = np.array([4,8,6])
arr29 = np.remainder(arr,arr1)
print("Use numpy.remainder() function")
print(arr29)

Substracting the two arrays:


[[-10 -9 -8]

11
[ -7 -6 -5]
[ -4 -3 -2]]
Multiplying the two arrays:
[[ 0 10 20]
[30 40 50]
[60 70 80]]
Dividing the two arrays:
[[0. 0.1 0.2]
[0.3 0.4 0.5]
[0.6 0.7 0.8]]
calculating exponents of an array of numbers:
[125 27 216 729 8 64]
Use numpy.reciprocal() function
[0.02 0.74626866 0.33333333 1. 0.04 ]
Use numpy.reciprocal() function
[0]
Use numpy.mod() function
[3 0 1]
Use numpy.remainder() function
[3 0 1]

1.7 Linear algebra


1.7.1 Input an matrix and determine: rank, trace, determinant, inverse of this

[ ]: import numpy as np
A = np.array([[6, 1, 1],
[4, -1, 6],
[4, 8, 9]])

# Rank of a matrix
print("Rank of A:", np.linalg.matrix_rank(A))

# Trace of matrix A
print("\nTrace of A:", np.trace(A))

# Determinant of a matrix
print("\nDeterminant of A:", np.linalg.det(A))

# Inverse of matrix A
print("\nInverse of A:\n", np.linalg.inv(A))

print("\nMatrix A raised to power 3:\n",


np.linalg.matrix_power(A, 3))

Rank of A: 3

Trace of A: 11

12
Determinant of A: -306.0

Inverse of A:
[[ 0.17647059 -0.00326797 -0.02287582]
[ 0.05882353 -0.13071895 0.08496732]
[-0.11764706 0.1503268 0.05228758]]

Matrix A raised to power 3:


[[336 162 228]
[406 162 469]
[698 702 905]]

1.7.2 Return dot product of two matrix

[ ]: a = np.array([[1,2],[3,4]])
b = np.array([[11,12],[13,14]])
print("Dot product: ")
print(np.dot(a,b))
print("Complex-conjugating dot product: ")
np.vdot(a,b)

Dot product:
[[37 40]
[85 92]]
Complex-conjugating dot product:

[ ]: 130

1.7.3 Return inner product of two arrays

[ ]: #Ordinary inner product for vectors:


a = np.array([1,2,3])
b = np.array([0,1,0])
np.inner(a, b)

[ ]: 2

[ ]: #Some multidimensional examples:


#Example 1
a = np.arange(24).reshape((2,3,4))
b = np.arange(4)
c = np.inner(a, b)
c.shape

[ ]: (2, 3)

13
[ ]: #Some multidimensional examples:
#Example 2
a = np.arange(2).reshape((1,1,2))
b = np.arange(6).reshape((3,2))
c = np.inner(a, b)
c.shape

[ ]: (1, 1, 3)

1.7.4 Return outer product of two vectors

[ ]: #Example 1
rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5))
rl
im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,)))
im
grid = rl + im
grid

[ ]: array([[-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j],


[-2.+1.j, -1.+1.j, 0.+1.j, 1.+1.j, 2.+1.j],
[-2.+0.j, -1.+0.j, 0.+0.j, 1.+0.j, 2.+0.j],
[-2.-1.j, -1.-1.j, 0.-1.j, 1.-1.j, 2.-1.j],
[-2.-2.j, -1.-2.j, 0.-2.j, 1.-2.j, 2.-2.j]])

[ ]: #Example 2
x = np.array(['a', 'b', 'c'], dtype=object)
np.outer(x, [1, 2, 3])

[ ]: array([['a', 'aa', 'aaa'],


['b', 'bb', 'bbb'],
['c', 'cc', 'ccc']], dtype=object)

1.7.5 Test the difference between np.matmul and np.dot

[ ]: #Example 1:
a = np.ones([9, 5, 7, 4])
b = np.ones([9, 5, 4, 3])
np.dot(a, b).shape
np.matmul(a, b).shape

[ ]: (9, 5, 7, 3)

[ ]: #Example 2:
a = [[1,0],[0,1]]
b = [1,2]
print (np.matmul(a,b))
print (np.matmul(b,a))

14
[1 2]
[1 2]

[ ]: #Example 3:
import numpy.matlib
import numpy as np

a = np.arange(8).reshape(2,2,2)
b = np.arange(4).reshape(2,2)
print (np.matmul(a,b))

[[[ 2 3]
[ 6 11]]

[[10 19]
[14 27]]]

2 DO IT YOURSELF
2.1 Create the following arrays:
• Create an array of 5 zeros.
• Create an array of 10 ones.
• Create an array of 5 3.141s.
• Create an array of the integers 1 to 20.
• Create a 5 x 5 matrix of ones with a dtype int.

2.2 Create an 3D matrix of 3 x 3 x 3 full of random numbers drawn from a


standard normal distribution . Then, reshape the above array into shape
(27,)
Hint: use np.random.randn() and np.reshape()

2.3 Create an array of 20 linearly spaced numbers between 1 and 10.


Hint: Use np.linspace()

2.4 Write expressions to extract the following sub-arrays of a 6x6 random array
with:
• rows 0, 1, and 2.
• rows 0, 1, and 5.
• columns 0, 1, and 2.
• columns 0, 1, and 3
• columns 0, 1, and 2 from rows 2 and 3.
• consisting of the odd rows and even columns

15
2.5 Write a program to create a 2d Numpy array as below:
[[0. 0. 0. 0. 0.]
[0. 1. 1. 1. 0.]
[0. 1. 1. 1. 0.]
[0. 1. 1. 1. 0.]
[0. 0. 0. 0. 0.]]

2.6 Run the following code to create an array of shape 4 x 4 and then use
indexing to produce the outputs shown below.
[]: import numpy as np
a = np.arange(1, 26).reshape(5, -1)

[ ]: 20

[ ]: # your answer

[ ]: array([[ 9, 10],
[14, 15],
[19, 20],
[24, 25]])

[ ]: # your answer

[ ]: array([ 6, 7, 8, 9, 10])

[ ]: # your answer

[ ]: array([[11, 12, 13, 14, 15],


[16, 17, 18, 19, 20]])

[ ]: # your answer

[ ]: array([[ 8, 9],
[13, 14]])

[ ]: # your answer

Calculate the sum of all the numbers in a.

[ ]: # your answer

Calculate the sum of each row in a.

[ ]: # your answer

Extract all values of a greater than the mean of a


Hint: Use a boolean mask

16
[ ]: # your answer

2.7 Write Python program to


• Create a numpy array with the values in the matrix below.
[[ 1 -5 6 -1 0]
[ 5 2 0 4 -2]
[-7 -7 1 -8 4]
[-5 7 2 -9 5]
[ 5 3 0 2 1]
[ 0 6 4 0 2]]
• Print the shape of the array
• Extract the elements:
– 3rd row, 4th column
– 6th row, 1st column
– 5th row, 2nd column

2.8 Find the location of the minimum value in the following array b:
Hint: Use the function argmin()

[]: np.random.seed(123)
b = np.random.randn(10)
b

[]: array([-1.0856306 , 0.99734545, 0.2829785 , -1.50629471, -0.57860025,


1.65143654, -2.42667924, -0.42891263, 1.26593626, -0.8667404 ])

[]: # your answer

2.9 Generate a 10 x 3 array of random numbers (in range [0,1]). For each row,
pick the number closest to 0.5.
• Use abs and argsort to find the column j closest for each row.
• Use fancy indexing to extract elements in the rows [0,1,2] and in the columns [2,3,1]

17
2.10 The array named pos has a shape of (6,2). Consider each row of pos is
used to store the position of an object. For example, pos[0,0] and pos[0,1]
store, respectively, the x- and y-coordinates of the first object. The array
elements ref [0] and ref [1] store, respectively, the x- and y-coordinates of
a reference point. The task is to compute the distance between each of
the 6 objects in pos from the reference point ref. This task is required
to complete using numpy functions and arithmetic operators. If the co-
ordinates of the object is (x,y) and those of the reference
p point are (a,b),
then their distance is given by the formula: (x − a)2 + (y − b)2 . Two
numpy arrays pos and ref are given as follows:
[ ]: pos = np.array([[ 1.72, 2.56],
[ 0.24, 5.67],
[ -1.24, 5.45],
[ -3.17, -0.23],
[ 1.17, -1.23],
[ 1.12, 1.08]])

ref = np.array([1.22, 1.18])

Hints: Use numpy broadcasting and some numpy mathematical functions (https://numpy.org/
doc/stable/reference/routines.math.html)

2.11 Create a two demensions array and make some statistic computation on
this array
[[45 61 65 44 1 18]
[ 7 4 58 58 66 78]
[16 95 39 1 90 33]
[40 41 79 67 40 86]]
The output results are presented as below:
* Min value for rows : [ 1 4 1 40]
* Min value for columns : [ 7 4 39 1 1 18]
* Max value for rows : [65 78 95 86]
* Max value for columns : [45 95 79 67 90 86]
- Min value of ARRAY : 1
- Max value of ARRAY : 95
- Mean value for rows : [39. 45.16666667 45.66666667 58.83333333]
- Mean value for rows : [27. 50.25 60.25 42.5 49.25 53.75]
- Mean value of ARRAY : 47.166666666666664
- StDeviation value for rows : [22.75228926 28.84681766 35.30659366 19.31680328]
- StDeviation value for columns : [15.92168333 32.94977238 14.41136704 25.32291452 32.99526481
- StDeviation value of ARRAY : 28.18933998675543
- Variance value for rows : [ 517.66666667 832.13888889 1246.55555556 373.13888889]
- Variance value for columns : [ 253.5 1085.6875 207.6875 641.25 1088.6875 834.1875]
- Variance value for ARRAY : 794.6388888888888

18
2.12 Write a function which takes two arrays of equal size and returns a array
of the same size where the ith element is True if the ith elements of the
two arrays are equal.
Example: given the arrays np.array([10, 20, 30]) and np.array([10, 30, 30]), the function
would return np.array([True, False, True]). Requirement: uses NumPy
Hint: Use the function where()
arrays and functions.

2.13 Write a function which takes two arrays of equal length and returns an
array of the indices where the elements of the two arrays are equal.
Example: given the arrays np.array([10, 20, 30]) and np.array([10, 30, 30]), the function
would return np.array([0, 2]).
Requirement: uses NumPy arrays and functions.
Hint: Use the function where()

2.14 Write a function named clip_values which takes in an n-dimensional array


and returns a new array with its values clipped between min_val and
max_val.
Examples: clip_values(np.array([1, 2, 3]), min_val=2) would return np.array([2, 2, 3] and
clip_values(np.array([1, 2, 3]), max_val=2) would return np.array([1, 2, 2].
Requirement: return a new array and to not modify the input array.

2.15 Solve the linear system Ax = b using Python numpy.



2x1 − x2 + x3 = −1

3x1 + 3x2 + 9x3 = 0 (1)

3x1 + 3x2 + 5x3 = 4

2.16 Check the answer by multiplying the matrix A by the solution vector x,
subtract the vector b. Print the difference vector. Then take the Euclidean
norm (length) of the difference vector. That is, calculate d = Ax-b and
|d| = |Ax - b|.
Hint: Don’t use * when multiplying matrix with a vector. Use the np.dot function instead.

19
2.17 Write a function add_row(A,s,i,j) that takes as input parameters a numpy
array representing the matrix A , a number s , and integers i and j and
returns the numpy array resulting from adding s times i row to j row.
Do not need to check whether the indices and are valid, but should make
sure that the output is correct for i =j.
2.18 Write a function inverse_matrix(A) that computes the inverse of a matrix
using Gauss elimination.
Hint : Assume that the matrix is invertible.

2.19 Write a NumPy program to calculate the QR decomposition of a given


matrix
Hint: Use numpy.linalg.qr()
More information: https://mathworld.wolfram.com/QRDecomposition.html

2.20 Write a NumPy program to compute the sum of the diagonal element of
a given array
Hint: Use numpy.trace()

2.21 Write a NumPy program to compute the eigenvalues and right eigenvec-
tors of a given square array
Hint: Use numpy.linalg.eig()
More information: https://mathworld.wolfram.com/Eigenvalue.html

20

You might also like