#C10727. Matrix Operations: Implementation and Computation
Matrix Operations: Implementation and Computation
Matrix Operations: Implementation and Computation
You are required to implement a Matrix
class to perform various matrix operations. The supported operations are:
- Addition (
ADD
): Computes the sum of two matrices of the same dimensions. - Subtraction (
SUB
): Computes the difference between two matrices of the same dimensions. - Multiplication (
MUL
): Computes the product of two matrices where the number of columns in the first equals the number of rows in the second. - Transpose (
TRANS
): Computes the transpose of a given matrix. - Determinant (
DET
): Calculates the determinant of a matrix. This operation is defined only for 2x2 and 3x3 matrices. For a 2x2 matrix \(\begin{bmatrix} a & b \\ c & d \end{bmatrix}\), the determinant is given by \(ad - bc\). For a 3x3 matrix \(\begin{bmatrix} a & b & c \\ d & e & f \\ g & h & i \end{bmatrix}\), the determinant is defined as \(a(ei - fh) - b(di - fg) + c(dh - eg)\). - String representation (
STR
): Outputs the matrix in row-major order. Each row is printed in a separate line with elements separated by a single space.
Your implementation must read the input from standard input and output the results to standard output. The input will specify an operation code followed by matrix dimensions and the matrix data. The operations should be executed accordingly and the result printed.
inputFormat
The input starts with an operation code, which can be one of the following: ADD
, SUB
, MUL
, TRANS
, DET
, or STR
.
Depending on the operation, the subsequent input format is as follows:
- ADD and SUB:
- An integer
r
and an integerc
denoting the number of rows and columns for matrix 1. r
lines follow, each containingc
space-separated integers.- The next line contains two integers
r
andc
(same dimensions) for matrix 2. r
lines follow for matrix 2.
- An integer
- MUL:
- First, two integers
r
andc
for the dimensions of the first matrix. - Then
r
lines each withc
integers. - Next, two integers:
c
(number of rows for the second matrix, matching previous matrix's column) and an integerk
(number of columns for the second matrix). - Then
c
lines each withk
integers.
- First, two integers
- TRANS, DET, and STR:
- Two integers
r
andc
specifying the number of rows and columns of the matrix. r
lines follow withc
space-separated integers.
- Two integers
outputFormat
For operations ADD
, SUB
, MUL
, TRANS
, and STR
, output the resulting matrix with each row on a new line and elements separated by a single space.
For the DET
operation, output a single integer representing the determinant.
ADD
2 2
1 2
3 4
2 2
5 6
7 8
6 8
10 12
</p>