Ques . write a program to Implement addition , subtraction , transpose and multiplication in a matrix
Answer :
matrix is referred as a arrangement of numbers in rows and columns in which each number or a element is called matrix element .
Dimension of matrix : No. of rows X No. of columns .
Example : [2,3]
[1,2]
therefore , dimension = 2 X 2 = 2 rows and 2 columns .
Algorithm to add two matrices
- Input matrix X and matrix Y.
- If the number of rows and number of columns of matrix X and matrix Y is equal,
- for i =1 to rows [matrix X]
- for j =1 to columns [matrix X]
- Input matrix X [i,j]
- Input matrix Y [i,j]
- matrix Result [i, j] = matrix X [i, j] + matrix Y [i, j];
3. Display matrix Result [i,j]
Example :
X=[1,2,3] Y=[2,3,4]
[0,1,0] [4,4,4]
Result = [1+2,2+3,3+4] = [3,5,7]
[0+4,1+4,0+4] = [4,5,4]
Algorithm to subtract two matrices
- Input matrix X and matrix Y.
- If the number of rows and number of columns of matrix X and matrix Y is equal,
- for i =1 to rows [matrix X]
- for j =1 to columns [matrix X]
- Input matrix X [i,j]
- Input matrix Y [i,j]
- matrix Result [i, j] = matrix X [i, j] - matrix Y [i, j];
3. Display matrix Result [i,j]
Example :
X=[1,2,3] Y=[2,3,4]
[0,1,0] [4,4,4]
Result = [1-2,2-3,3-4] = [-1,-1,-1]
[0-4,1-4,0-4] = [-4,-3,-4]
Algorithm to perform matrix multiplication
- Input the matrix X elements
- Input the matrix Y elements
- Repeat from i = 0 to the length of the first matrix
- Repeat from j = 0 to the length of the first element
- Repeat from k = 0 to the length of the second matrix
- Result[i][j] += matrix X[i][j] * matrix Y[i][j]
- Print matrix Result
- End
Example : X = [[10, 9] [8, 6]]
Y = [[1, 2], [3, 4]]
XY= [(10*1+9*3) , (10*2+9*4)] = [37, 56]
[(8*1+6*3) , (8*2+6*4) ] = [26, 40]
Example to transpose of matrix :
1 2 3
4 5 6
7 8 9
output:
1 4 7
2 5 8
3 6 9
Column wise addition, subtraction, multiplication and transpose :
X = [[1,2,3], [2 ,5,6], [7 ,8,9]] Y = [[9,8,7], [6,5,4], [3,2,1]] result = [[0,0,0], [0,0,0], [0,0,0]] #addition for i in range(len(X)): for j in range(len(X[0])): result[i][j] = X[i][j] + Y[i][j] for r in result: print(r)
#subtraction for i in range(len(X)): for j in range(len(X[0])): result[i][j] = X[i][j] - Y[i][j] for r in result: print(r)
#multiplication for i in range(len(X)): for j in range(len(Y[0])): for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] for r in result: print(r)
#transpose for i in range(len(X)): for j in range(len(X[0])): result[j][i] = X[i][j] for r in result: print(r) |
---|
Output :
[10, 10, 10]
[8, 10, 10]
[10, 10, 10]
[-8, -6, -4]
[-4, 0, 2]
[4, 6, 8]
[22, 18, 14]
[62, 53, 42]
[142, 120, 98]
[1, 2, 7]
[2, 5, 8]
[3, 6, 9]
For more Rajasthan Technical University CSE-III Sem DSA Lab Experiments CLICK HERE