Source code for vectors
import numpy as np
import copy
import time
[docs]def matrix_as_lists(nx, ny):
"""
Create a 'matrix' of ones as a list of lists.
Args:
nx (int): number of columns (horizontal size)
ny (int): number of rows (vertical size)
Returns:
list: table of ones
"""
# could this be done in another way?
matrix = [ [ 1 ] * nx ] * ny
return matrix
[docs]def matrix(nx, ny):
"""
Create a matrix of ones as a numpy array.
.. note ::
This function is incomplete!
Args:
nx (int): number of columns (horizontal size)
ny (int): number of rows (vertical size)
Returns:
list: matrix of ones
"""
matrix = None # todo
return matrix
[docs]def change_center_element_in_place(matrix, value):
"""
Change the center element of the matrix to the given value.
The change is derectly applied on the given matrix.
Args:
matrix (list or array): the matrix
value (float): new value
"""
nx = len(matrix[0])
ny = len(matrix)
kx = nx//2
ky = ny//2
# For a numpy array, matrix[ky,kx] works.
# For a list of lists, it does not and
# you must use matrix[ky][kx].
matrix[ky][kx] = value
[docs]def change_center_element(matrix, value):
"""
Change the center element of the matrix to the given value.
The given matrix is not affected. Instead, a new matrix is returned.
Args:
matrix (list or array): the matrix
value (float): new value
Returns:
array or list: new matrix
"""
nx = len(matrix[0])
ny = len(matrix)
kx = nx//2
ky = ny//2
# We make a copy of the original matrix
# to make sure we don't accidentally make
# changes to it.
new_matrix = copy.deepcopy(matrix)
new_matrix[ky][kx] = value
return new_matrix
[docs]def multiply_by_scalar(matrix, scalar):
"""
Multiplies the matrix by a scalar.
The function checks whether the given matrix is a
true numpy array or just a table made of lists.
If the matrix is an array, the operation is executed
as a single vector command. If the matrix is a table,
the only option is to loop over all elements.
Args:
matrix (list or array): the matrix
scalar (float): multiplier
"""
if type(matrix) is np.ndarray:
matrix *= scalar
else:
nx = len(matrix[0])
ny = len(matrix)
for i in range(ny):
for j in range(nx):
matrix[i][j] *= scalar
[docs]def add_scalar(matrix, scalar):
"""
Adds a scalar to a matrix.
The function checks whether the given matrix is a
true numpy array or just a table made of lists.
If the matrix is an array, the operation is executed
as a single vector command. If the matrix is a table,
the only option is to loop over all elements.
Args:
matrix (list or array): the matrix
scalar (float): added value
"""
if type(matrix) is np.ndarray:
matrix += scalar
else:
nx = len(matrix[0])
ny = len(matrix)
for i in range(ny):
for j in range(nx):
matrix[i][j] += scalar
[docs]def print_matrix(matrix, name):
"""
Prints a matrix in a tabulated format.
For numpy arrays, printing automatically produces
a nice matrix-like representation, but lists are printed
on one line. This function will tabulate both.
Args:
matrix (list or array): the matrix
name (str): the title printed before the actual matrix
"""
nx = len(matrix[0])
ny = len(matrix)
print()
print( str(name)+" = " )
for i in range(ny):
line = ""
for j in range(nx):
line += str( matrix[i][j] ) +" "
print(line)
[docs]def main( nx, ny, printout = True ):
"""
The main function.
Creates a matrix both as a list of lists and a numpy array and
performs similar operations on both.
The first operation is changing the center element of the
matrix using either :meth:`change_center_element`
or :meth:`change_center_element_in_place`.
The second operation is multiplying the matrix with a scalar
with :meth:`multiply_by_scalar`.
The function times the multiplication for both matrices and
returns the required time in seconds.
.. note ::
This function is incomplete!
Args:
nx (int): number of columns (horizontal size)
ny (int): number of rows (vertical size)
printout (bool): if True, the matrices are printed after each step
Returns:
float, float: multiplication time for a table, for a matrix
"""
# mL is a list of lists
mL = matrix_as_lists(nx, ny)
# mN is a proper matrix
mN = matrix(nx, ny)
if printout:
print_matrix(mL, "list array initially")
print_matrix(mN, "numpy array initially")
###
#
# ToDo: change the center element of both mL and mN.
#
##
if printout:
print_matrix(mL, "list array after element change")
print_matrix(mN, "numpy array after element change")
# start timing
start_time = time.time()
# multiply list by looping over all elements
multiply_by_scalar(mL,5)
# checkpoint
mid_time = time.time()
# multiply matrix with a vectorized method
multiply_by_scalar(mN,5)
# finish timing
end_time = time.time()
if printout:
print_matrix(mL, "list array after multiplication")
print_matrix(mN, "numpy array after multiplication")
return mid_time-start_time, end_time-mid_time
# The following commands are executed if the code is
# launched as the main program. They will be ignored
# if the code is imported as a module.
if __name__ == "__main__":
list_time, vector_time = main(5, 3)
print("list iteration took "+str(list_time)+" s")
print("vector operation took "+str(vector_time)+" s")