KEMBAR78
Lecture 7 | PDF | Matrix (Mathematics) | Multiplication
0% found this document useful (0 votes)
7 views35 pages

Lecture 7

The document covers various topics related to arrays in programming, including creating lists using range(), performing simple statistics, and utilizing NumPy for mathematical operations with arrays. It explains list comprehensions, slicing, and addressing arrays, as well as multi-dimensional arrays and matrix operations. Additionally, it includes quizzes and tasks to reinforce the concepts learned.
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)
7 views35 pages

Lecture 7

The document covers various topics related to arrays in programming, including creating lists using range(), performing simple statistics, and utilizing NumPy for mathematical operations with arrays. It explains list comprehensions, slicing, and addressing arrays, as well as multi-dimensional arrays and matrix operations. Additionally, it includes quizzes and tasks to reinforce the concepts learned.
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/ 35

Logika Pemrograman

Pertemuan 7
Pertemuan 7 Arrays (cont’d)

• Using range()to make a list of numbers


• Simple statistics with a List of numbers
• List comprehensions
• NumPy arrays
• Mathematical operation with arrays
• Slicing and addressing arrays
• Multi-dimensional arrays and matrices
• Quiz
Using range()to make a list of numbers

• If you want to make a list of numbers, you can convert the results of range()
directly into a list using the list() function.
• When you wrap list()around a call to the range()function, the output will
be a list of numbers.
numbers = list(range(1, 6))
print(numbers)

even_numbers = list(range(2, 11, 2))


print(even_numbers)

[1, 2, 3, 4, 5]
[2, 4, 6, 8, 10]
Using range()to make a list of numbers

• Make a list of the first 10 square numbers (that is, the square of each integer from
1 through 10).

squares = []
for value in range(1,11):
squares.append(value**2)
print(squares)

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


Simple statistics with a List of numbers

• A few Python functions are helpful when working with lists of numbers.
• For example, you can easily find the minimum, maximum, and sum of a
list of numbers:
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits))
print(max(digits))
print(sum(digits))

0
9
45
List comprehensions
• The approach described earlier for generating the list squares consisted
of using three or four lines of code.

• A list comprehension allows you to generate this same list in just one line
of code.

squares = [value**2 for value in range(1, 11)]


print(squares)

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


• Adding lists concatenates them, just as the “+” operator concatenates
strings.

a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9, 0]
print(a+b)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
NumPy arrays
• The NumPy array is the real workhorse of data structures for scientific
and engineering applications.
• The NumPy array, formally called ndarray in NumPy documentation, is
similar to a list but where all the elements of the list are of the same
type.

Creating arrays (1-d)

• NumPy has a number of functions for creating arrays.

• The first of these, the array function, converts a list to an array:


a = [0, 0, 1, 4, 7, 16, 31, 64, 127]
import numpy as np
b = np.array(a)
print(b)
c = np.array([1, 2.5, 5, 7, 9, 0, 1, 2, 3])
print("\n",c)

[ 0 0 1 4 7 16 31 64 127]

[1. 2.5 5. 7. 9. 0. 1. 2. 3. ]

• Notice that b is an integer array, as it was created from a list of integers.


• On the other hand, c is a floating point array even though only one of
the elements of the list from which it was made was a floating number.
• The second way arrays can be created is using the NumPy linspace or
logspace functions.

• The linspace function creates an array of N evenly spaced points


between a starting point and an ending point.

• The form of the function is linspace(start, stop, N). If the


third argument N is omitted, then N=50.

g = np.linspace(0, 10, 5)
print(g)

[ 0. 2.5 5. 7.5 10. ]


• The linspace function produced 5 evenly spaced points between 0 and 10
inclusive.
• NumPy also has a closely related function logspace that produces evenly spaced
points on a logarithmically spaced scale.
• The arguments are the same as those for linspace except that start and stop refer
to a power of 10. That is, the array starts at 10start and ends at 10stop.

h = np.logspace(1, 3, 5)
print(h)

[ 10. 31.6227766 100. 316.22776602 1000. ]

• The logspace function created an array with 5 points evenly spaced on a


logarithmic axis starting at 101 and ending at 103. The logspace function is
particularly useful when you want to create a log-log plot.
• The third way arrays can be created is using the NumPy arange function.
• The form of the function is arange(start, stop, step). If the third
argument is omitted step=1. If the first and third arguments are omitted, then
start=0 and step=1.
j = np.arange(0, 10, 2)
print(j)
k = np.arange(0., 10, 2)
print(k)
l = np.arange(0, 10, 1.5)
print(l)

[0 2 4 6 8]
[0. 2. 4. 6. 8.]
[0. 1.5 3. 4.5 6. 7.5 9. ]
• The arange function produces points evenly spaced between 0 and 10
exclusive of the final point.

• Notice that arange produces an integer array in the first case but a
floating point array in the other two cases.

• In general arange produces an integer array if the arguments are all


integers; making any one of the arguments a float causes the array that
is created to be a float.
Mathematical operations with arrays
• The utility and power of arrays in Python comes from the fact that you
can process and transform all the elements of an array in one fell swoop
a = np.linspace(-1, 5, 7)
print(a)

b = a*6
print(b)

[-1. 0. 1. 2. 3. 4. 5.]
[-6. 0. 6. 12. 18. 24. 30.]
f = a - 10
print(f)

g = (a + 3)*2
print(g)

h = np.sin(a)
print(h)

[-11. -10. -9. -8. -7. -6. -5.]


[ 4. 6. 8. 10. 12. 14. 16.]
[-0.84147098 0. 0.84147098 0.90929743 0.14112001 -0.7568025 -0.95892427]
a = np.arange(0, 10, 2)
print(a)
b = np.arange(1, 11, 2)
print(b)
print(a+b)
print(a*b)
print(a/b)

[0 2 4 6 8]
[1 3 5 7 9]
[ 1 5 9 13 17]
[ 0 6 20 42 72]
[0. 0.66666667 0.8 0.85714286 0.88888889]
Slicing and addressing arrays
• Suppose, for example, that we have two arrays y, and t for position vs. time of a
falling object, say a ball, and we want to use these data to calculate the velocity as a
function of time:
y = np.array([0., 1.3, 5. , 10.9, 18.9, 28.7, 40.])
t = np.array([0., 0.49, 1. , 1.5 , 2.08, 2.55, 3.2])
• We can find the average velocity for time interval i by the formula:

• We can easily calculate the entire array of velocities using the slicing and vectorized
subtraction properties of NumPy arrays by noting that we can create two y arrays
displaced by one index.
#Program to calculate the average velocity

import numpy as np
y = np.array([0., 1.3, 5. , 10.9, 18.9, 28.7, 40.])
print('y position =',y)
t = np.array([0., 0.49, 1. , 1.5 , 2.08, 2.55, 3.2])
print('\ntime =',t)
y_b = y[:-1]
print('\ny_i-1 =',y_b)
y_p = y[1:]
print('\ny_i =',y_p)
delta_y = y_p - y_b
print('\ndifference in y =',delta_y)
t_b = t[:-1]
print('\nt_i-1 =',t_b)
t_p = t[1:]
print('\nt_i =',t_p)
delta_t = t_p - t_b
print('\ndifference in t =', delta_t)
vel = delta_y/delta_t
print('\naverage velocity =', vel)
y position = [ 0. 1.3 5. 10.9 18.9 28.7 40. ]

time = [0. 0.49 1. 1.5 2.08 2.55 3.2 ]

y_i-1 = [ 0. 1.3 5. 10.9 18.9 28.7]

y_i = [ 1.3 5. 10.9 18.9 28.7 40. ]

difference in y = [ 1.3 3.7 5.9 8. 9.8 11.3]

t_i-1 = [0. 0.49 1. 1.5 2.08 2.55]

t_i = [0.49 1. 1.5 2.08 2.55 3.2 ]

difference in t = [0.49 0.51 0.5 0.58 0.47 0.65]

average velocity = [ 2.65306122 7.25490196 11.8 13.79310345


20.85106383 17.38461538]
• These are the average velocities over each interval so the times best
associated with each interval are the times halfway in between the
original time array, which we can calculate using a similar trick of slicing:

tv = (t_p+t_b)/2.
print('\ntimes associated for each interval',tv)

times associated for each interval = [0.245 0.745


1.25 1.79 2.315 2.875]
Multi-dimensional arrays and matrices
• So far we have examined only 1-D NumPy arrays, that is, arrays that
consist of a simple sequence of numbers.

• However, NumPy arrays can be used to represent multidimensional


arrays.

• For example, you may be familiar with the concept of a matrix, which
consists of a series of rows and columns of numbers.

• Matrices can be represented using 2-D NumPy arrays.

• Higher dimension arrays can also be created as the application demands.


• There are a number of ways of creating multidimensional NumPy arrays.

• The most straightforward way is to convert a list to an array using


NumPy’s array function, which we demonstrate here:

b = np.array([[1., 4, 5], [9, 7, 4]])


print(b)

[[1. 4. 5.]
[9. 7. 4.]]
• Multidimensional arrays can also be created from one-dimensional
arrays using the reshape function.

• For example, a 2 × 3 array can be created as follows:


c = np.arange(6)
print(c)
c = np.reshape(c, (2,3))
print('\n',c)

[0 1 2 3 4 5]

[[0 1 2]
[3 4 5]]
Matrix operations
• Addition, subtraction, multiplication, division, and exponentiation all work with
multidimensional arrays the same way they work with one-dimensional arrays, on an
element-by-element basis, as illustrated below:
b = np.array([[1., 4, 5], [9, 7, 4]])
print(b)
c = 2*b
print(c)
d = b/4
Print(d)

[[1. 4. 5.]
[9. 7. 4.]]
[[ 2. 8. 10.]
[18. 14. 8.]]
[[0.25 1. 1.25]
[2.25 1.75 1. ]]
b = np.array([[1., 4, 5], [9, 7, 4]])
print(b)
e = b**2
print(e)
f = b-2
print(f)

[[1. 4. 5.]
[9. 7. 4.]]
[[ 1. 16. 25.]
[81. 49. 16.]]
[[-1. 2. 3.]
[ 7. 5. 2.]]
b = np.array([[1., 4, 5], [9, 7, 4]])
print(b)
c = np.reshape(c, (2,3))
print(c)
print(b*c)

[[1. 4. 5.]
[9. 7. 4.]]
[[0 1 2]
[3 4 5]]
[[ 0. 4. 10.]
[27. 28. 20.]]

• Beware: array multiplication, done on an element-by-element basis, is not the same


as matrix multiplication as defined in linear algebra.
• Therefore, we distinguish between array multiplication and matrix multiplication in
Python
• Normal matrix multiplication is done with NumPy’s dot function.

b = np.array([[1., 4, 5], [9, 7, 4]])


print(b)
c = np.array([[4, 2], [9, 8], [-3, 6]])
print(c)
g = np.dot(b,c)
Print(g)

[[1. 4. 5.]
[9. 7. 4.]]
[[ 4 2]
[ 9 8]
[-3 6]]
[[25. 64.]
[87. 98.]]
Quiz
(1) a. Create an array of 9 evenly spaced numbers going from 0 to 29
(inclusive) and give it the variable name r.

b. Find the square of each element of the array (as simply as


possible).

c. Find twice the value of each element of the array in two different
ways: (i) using addition and (ii) using multiplication.

Print out the array r and each output requested above


Quiz
(2) a. Create an array in 1-degree increments of all the angles in degrees
from 0 to 360 degrees inclusive.

b. an array from 12 to 17, not including 17, in 0.2 increments;

c. an array from 12 to 17, including 17, in 0.2 increments.


Quiz
(3)

Perform the following operations:

(a) (d)

(b) (e)

(c)
Tugas
(1)
Tugas
Tugas
(2)
Tugas

You might also like