Question

Question A matrix of dimensions m × n (an m-by-n matrix) is an ordered collection of m × n elements. which are called eernent·Matrix multiply Assume A is a m × k matrix and B is a k × n nnatrix, the product of AB is defined as You are asked to compleclass Matrix(object) def __init__(self, matrix): (Matrix, list)- NoneType creates a data attribute elements and instantiatedef __repr_(self): Do not change this. return self.--str def __eq_(self, other): (Matrix) -> bool Returns if the seldef mul(self, k): (Matrix, Matrix) -> Matrix Returns the scalar product of the input matrix with scalar k as a new matrix ondef trace(self): (Matrix) -> float Returns the trace of the input matrix as a floating point number. If the matrix is not squdef dot(self, other): (Matrix, Matrix) -> Matrix Returns a matrix product between self and other. If self and other has misma

Question A matrix of dimensions m × n (an m-by-n matrix) is an ordered collection of m × n elements. which are called eernents (or components). The elements of an (m × n)-dimensional matrix A are denoted as a,, where 1im and1 S, symbolically, written as, A-a(1,1) S (i.j) S(m, ). Written in the familiar notation: 01,1 am Gm,n A3×3matrix The horizontal and vertical lines of entries in a matrix are called rows and columns, respectively A matrix with the same nmber of rows and columns is called a square matrix Several operations are defined for matrices, you are asked to implement the following: .Addition: the matrix addition is defined as ab Matrices A and B must have same dimensions. For examp le: 2 6 10 4 5 6| +12 5 8 =14+2 5+5 6+5 -16 10 14 10 14 18 1+1 2+4 3+ 3 6 9 7+3 8+6 9+9 Scaler multiplication Matrix A multiplied by scaler k is defined as kxa example: For 2. 4 5 6 8 10 12 14 16 18 as, wherei Trace The trace of a square matriz is the sum of its diagonal elements, namely j. For instance tr 4 5 61+5+9-15 anspose The transpose of a matrix is simply inverting the column and rows, namely a,,-01, Fr instance. 2 4 5 62 5 8 3 6 9
·Matrix multiply Assume A is a m × k matrix and B is a k × n nnatrix, the product of AB is defined as You are asked to complete the implementation of a Python dass that can be used to represent matrices and perform various operations on them. The elements of a matrix are passed as a nested list to the constructor of the class, e.g., Matrix(E[1, 2, 3], [4, 5, 6], 17, 8, 9]]) creates an object representing the mat rix 1 2 3 4 5 6 7 89 In the code you impleent, make sure to check whether the matrices dimensions match so that the computation can be carried out. Pay attention to the bold italic font. In any case the operation is invalid (dimension mismatch, for instance), return an empty Matrix, namely with zero row and zero column. If the matrix passed to operator trace is not a square matrix, return float('inf) Note: you should write your own code for all the matrix operations. Do not import non-default python library like numpy. Follow the docstring provided to you, closely TODO: Download the file lab8.py, complete the functions inside according to their de- scriptions and upload your version of lab8.py to MarkUs. Feel free to add new helper func- tions/methods, but al the functions defined for you should be implemented.
class Matrix(object) def __init__(self, matrix): '"(Matrix, list)- NoneType creates a data attribute elements and instantiate it to the matrix Preconditions: list e contains 2 sublists, all the sublists in e have the same length Complete the instance variable definitions DO NOT CHANGE THE VARIABLE NAMES. Feel free to add new ones self.elements matrix self.cols -... # number of columns self, rows # number of rows def __str__(self): ''"(Matrix) -> str returns a string representation of the elements of the matrix. When passed to print) this representation should result in the original matrix being displayed as fbllows: each row will be displayed on a separate line, with each element in a row separated from the next by one, and only one blank space. The string representation should not contain any additional blank spaces. Print nothing if the matrix is empty >>>print(MatrixCIC1,2], [3,4]])]) 1 2 >>> print(Matrix([[0,-1.5,2.0], [-1, 4.5, 0]])) 1 4.50 >>>print(MatrixCEDI)) pass
def __repr_(self): """Do not change this.""" return self.--str def __eq_(self, other): '""(Matrix) -> bool Returns if the self matrix is equal Celementwise) to the other matrix >>>Matrix(E[1,1], 01,1]])Matrix(EC1,1], [1,1]]) True >>>Matrix(E[1,1], 01,2]])Matrix(EC1,1], [1,1]]) False pass def add(self, other): '""(Matrix, Matrix) -> Matrix Returns the result Cas a new Matrix object) of adding the second input Matrix to the first. Return an empty matrix if the matrices has mismatching sizes >>>Matrix(E[1,1], 01,1]]).add(Matrix(CL-1,3], [0,0]])) >>>MatrixCEC-1,3,0], [0,0,0], 01.5,1,1]]).add(Matrix(L[2,-0.5,1], [0,0,0], L0,0,11])) 1 2.5 1 1.5 1 2 pass
def mul(self, k): "(Matrix, Matrix) -> Matrix Returns the scalar product of the input matrix with scalar k as a new matrix onject. >>>Matrix(E[1,1], 01,1]]).mul(1) >>>Matrix(E[1,3], [-2,-1]]).mulC-1) 2 1 pass def sub(self, other): '""(Matrix, Matrix) -> Matrix Returns the result Cas a new Matrix object) of subtract the second input Matrix to the first. Return an empty matrix if the matrices has mismatching sizes. >>>Matrix(E[1,1], 01,1]]).sub(Matrix(CL-1,3], [0,0]])) 2-2 >>>MatrixCEC-1,3,0], [0,0,0], 01.5,1,1]]).sub(Matrix(L[2,-0.5,1], [0,0,0], L0,0,11])) 3 3.5-1 1.5 1 0 pass
def trace(self): (Matrix) -> float Returns the trace of the input matrix as a floating point number. If the matrix is not square, return float('inf MatrixCE01,1], 02,21]).traceC) MatrixCCC-1,3,0],o,0,0],[1.5,1,1]]).trace 3.0 0.0 pass def transpose(self): (Matrix) -> Matrix Returns the transpose of the input matrix as a new Matrix object. MatrixCEC1,2], [3,411).transposeC) 1 3 2 4 pass
def dot(self, other): (Matrix, Matrix) -> Matrix Returns a matrix product between self and other. If self and other has mismatching dimension, return an empty Matrix object. If not, return the result of self (dot) other >AMatrixcEC1,2], [3,4], [5,6]]) >A.dot(A.transposeO) 11 25 39 17 39 61 pass
0 0
Add a comment Improve this question Transcribed image text
Answer #1

A): Programming code for Matrix Addition %%%%%% Using nested loop%%%%%%%

X = [[12,7,3], [4 ,5,6], [7 ,8,9]]

Y = [[5,8,1], [6,7,3], [4,5,9]]

result = [[0,0,0], [0,0,0], [0,0,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]

for r in result:
print(r)

Output:

[17, 15, 4]
[10, 12, 9]
[11, 13, 18]
B):Programming code for Matrix Scalar Multiplication

%%%% product of a matrix

%%%%%Size of given matrix

N = 3

def scalarProductMat( mat, k):

%%%%%scalar element is multiplied

%%%%% by the matrix

for i in range( N):

for j in range( N):

mat[i][j] = mat[i][j] * k   

%%%% Driver code

if _name_ == "__main__":

mat = [[ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]

k = 4

scalarProductMat(mat, k)

%%%% to display the resultant matrix

print("Scalar Product Matrix is : ")

for i in range(N):

for j in range(N):

print(mat[i][j], end = " ")

Output:

Scalar Product Matrix is :
4 8 12
16 20 24
28 32 36
C)Programming code for Matrix Trace:

import math

%%%% Size of given matrix

MAX = 100;

Returns trace of a matrix of

%%%% size n x n

def findTrace(mat, n):

sum = 0;

for i in range(n):

sum += mat[i][i];

return sum;

%%%%%Driver Code

mat = [[1, 1, 1, 1, 1],

[2, 2, 2, 2, 2],

[3, 3, 3, 3, 3],

[4, 4, 4, 4, 4],

[5, 5, 5, 5, 5]];

print("Trace of Matrix =", findTrace(mat, 5));

print("Normal of Matrix =", findNormal(mat, 5));

Output:

Trace of matrix = 15
D):Programming code for Matrix Transpose:

X = [[12,7], [4 ,5], [3 ,8]]

result = [[0,0,0], [0,0,0]]

%%%%% iterate through rows
for i in range(len(X)):
%%%%iterate through columns
for j in range(len(X[0])):
result[j][i] = X[i][j]

for r in result:
print(r)

Output:

[12, 4, 3]
[7, 5, 8]
E)Programming code forMatrix Multiplication:

%%%%% Matrix of order 3x3
X = [[12,7,3], [4 ,5,6], [7 ,8,9]]
%%%% Matrix of order 3x4
Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1]]
%%%% Result is of order 3x4
result = [[0,0,0,0], [0,0,0,0], [0,0,0,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]

for r in result:
print(r)

Output:

[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]

Add a comment
Know the answer?
Add Answer to:
Question A matrix of dimensions m × n (an m-by-n matrix) is an ordered collection of m × n elemen...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Problem: Matrix Implementation Create a class Matrix with the following method stubs for the following methods...

    Problem: Matrix Implementation Create a class Matrix with the following method stubs for the following methods described: 1. read: reads in a matrix from the command line 2. display: prints the matrix to the command line 3. getRows: returns the number of rows 4. getCols: returns the number of columns 5. set: sets the double value at a particular column/row position 6. get: returns the value stored at a particular column/row position 7. Plus: returns a new Matrix object that...

  • Recall that if A is an m times n matrix and B is a p × q matrix

    Recall that if A is an m times n matrix and B is a p × q matrix, then the product C = AB is defined if and only if n = p. in which case C is an m × q matrix.  a. Write a function M-file that takes as input two matrices A and B, and as output produces the product by rows of the two matrices. For instance, if A is 3 times 4 and B is...

  • Question 1 a. Define the following matrices in a script file (M-file), ? = ( 8...

    Question 1 a. Define the following matrices in a script file (M-file), ? = ( 8 9 10 11; 23 9 16 15 ;11 12 3 6; 1 2 8 9 ) ? = ( 2 21 7 15; 12 4 8 22; 23 9 5 13; 23 4 21 22) ℎ = (4 9 12 15) b. Add suitable lines of codes to the M-file to do the following. Each of the following points should be coded in only...

  • Iterators provide a systematic way to access all of the elements in a collection. To define...

    Iterators provide a systematic way to access all of the elements in a collection. To define an iterator, we need to add the __iter__() method to the class over which we want to iterate. Consider the following lines of code: odd_numbers = Odds(9) for num in odd_numbers: print(num) This code iterates over all the odd numbers less than or equal to 9 starting from the number 1. It assumes that the Odds class is iterable, i.e., it contains an __iter__()...

  • Given a matrix with m rows and n columns, m adjacent numbers are chosen from m...

    Given a matrix with m rows and n columns, m adjacent numbers are chosen from m rows, where two numbers are adjacent to each other if they are directly connected vertically or diagonally and only one number is taken from one row. Design a dynamic programming algorithm to find the smallest sum of these m numbers. For example, given a 3 by 3 matrix 1 2 3 4 5 6 7 0 2 The sum of three numbers 1, 4,...

  • MATLAB HELP!!! Recall that if A is an m × n matrix and B is a p × q matrix, then the product C = AB is defined if and on...

    MATLAB HELP!!! Recall that if A is an m × n matrix and B is a p × q matrix, then the product C = AB is defined if and only if n = p, in which case C is an m × q matrix. 5. Recall that if A is an mx n matrix and B is a px q matrix, then the product C-AB is defined if and only if n = p, in which case C is...

  • Finish each function python 3 LList.py class node(object): """ A version of the Node class with...

    Finish each function python 3 LList.py class node(object): """ A version of the Node class with public attributes. This makes the use of node objects a bit more convenient for implementing LList class.    Since there are no setters and getters, we use the attributes directly.    This is safe because the node class is defined in this module. No one else will use this version of the class. ''' def __init__(self, data, next=None): """ Create a new node for...

  • Write a function Transpose that transposes a matrix T with M rows and N colums. The...

    Write a function Transpose that transposes a matrix T with M rows and N colums. The transposed matrix, TT, should have N rows and M columns. Example. Given the matrix T. (C++14) Example: 1 2 3 0 -6 7 The transposed matrix TT is 1 0 2 -6 3 7 DEFAULT CODE: Add to code as needed: #include <iostream> #include <string> #include <cmath> using namespace std; void Transpose(int T[100][100], int TT[100][100], int M, int N) { int i; int j;...

  • Implement a C++ class to model the mathematical operations of a matrix. Your class should include...

    Implement a C++ class to model the mathematical operations of a matrix. Your class should include the following functions. add() which adds two matrices: power() which raises the first matrix to power n: "" which returns true if both matrices are equal. You need to overload the C++ equality operator. A sample run follows. Enter the number of rows: 2 Enter the number of columns: 3 Enter the elements of matrix 1 row by row: 1 5 0 1 3...

  • R assignment In the matrix() function: . The first argument is the collection of elements that...

    R assignment In the matrix() function: . The first argument is the collection of elements that R will arrange into the rows and columns of the matrix. Here, we use 1:9 which is a shortcut for c(1, 2, 3, 4, 5, 6, 7, 8, 9) e The argument byrow indicates that the matrix is filled by the rows. If we want the matrix to be filled by the columns, we just place byrow FALSE. . The third argument nrow indicates...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT