In: Computer Science
In python and comments your code :
Exercise 1
1.Write a function waiting for two matrices and returning their
addition, −1 if it is not not possible.
2. Write a function associated with a matrix and a scalar and
returning the produced matrix.
3. Write a function accompanying an n × m matrix and a vector n and
returning the vector produced by each other, −1 if this is not
possible.
4. Write a function accompanying two n × m and m × k matrices and
returning the product matrix, −1 if this is not possible.
5.Write a function waiting for a vector (column or row) and
returning its transpose.
Exercise 2
1.Write a function waiting for a 2 × 2 matrix and calculating
its determinant.
2. Write a function waiting for a matrix A of size n × m and two
integers i and j and rendering a matrix (n − 1) × (m − 1), copy the
matrix A without row i and column j .
3. Write a determining function of a square matrix by expanding on
a line.
1. Function for addition:
def addition(x,y):
if len(x)!=len(y) or len(x[0])!=len(y[0]):
return -1
result = [[ 0 for i in range(len(x))] for j in range(len(x[0]))]
#iterate through rows
for i in range(len(x)):
#iterate through columns
for j in range(len(x[0]):
result[i][j] = x[i][j]+y[i][j]
return result
2. Function for Matrix multiplied with Scalar:
def scalarMultiply(x, scalar):
#traversing through rows
for i in range(len(x)):
#traversing through columns
for j in range(len(y)):
#multiplying with scalar
x[i][j]*=scalar
return scalar
3. Function for multiplication of vector with matrix:
def matrixMultiplication(X,Y):
result = [[0 for i in range(len(X))] for j in range(len(Y[0]))]
# iterate through rows of X
for i in range(len(X)):
#iterate through columns of Y
for j in range(len(Y[0])):
#iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
def vectorMatrix(x, vector):
#checking if vector is a column vector
if len(vector[0])==len(x):
result = matrixMultiplication(vector,x)
#checking if vector is a row vector
elif len(x[0])==len(vector):
result = matrixMultiplication(x,vector)
#The matrix and the vector can't be multiplied
else
result = -1
return result
4. Function for Matrix Multiplication:
def matrixMultiplication(X,Y):
#Matrices cannot be multiplied
if len(X[0])!=len(Y):
return -1
result = [[0 for i in range(len(X))] for j in range(len(Y[0]))]
# iterate through rows of X
for i in range(len(X)):
#iterate through columns of Y
for j in range(len(Y[0])):
#iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
return result
5. Function for transpose of a vector:
def transposeVector(vector):
result = [[0 for i in range(vector)] for j in range(vector[0])]
#iterate through rows
for i in range(len(vector)):
#iterate through columns
for j in range(len(vector[0])):
result[j][i] = vector[i][j]
return result