This project is a Python program that performs basic matrix operations using input from a text file.
The program reads matrix data and an operation from input.txt, processes the matrices using a separate matrix library (matrix.py), and writes the result to output.txt.
The implementation separates input/output handling from matrix computation, keeping the matrix algorithms in a dedicated module.
This program was originally developed as part of a programming exercise focused on learning how to:
- read data from text files
- write results to output files
- validate structured input
- organize code using a separate module
Because of this requirement, the program uses file-based input (input.txt) and output (output.txt) instead of user input.
The program supports the following matrix operations:
| Operation | Description |
|---|---|
add |
Adds two matrices of the same dimensions |
multiply |
Performs matrix multiplication |
scalMultiply |
Multiplies a matrix by a scalar constant |
transpose |
Computes the transpose of a matrix |
matrix-operations/
├─ main.py # main program handling file input/output
├─ matrix.py # matrix operations library
├─ input.txt # input file containing operation and matrices
├─ output.txt # file where results are written
└─ README.md
Handles:
- reading input from file
- validating matrix dimensions
- constructing matrix data structures
- calling functions from
matrix.py - writing results to
output.txt
Contains the implementations of:
- matrix addition
- scalar multiplication
- matrix multiplication
- matrix transpose
All input is provided through the file:
input.txt
The first line specifies the operation.
operation
The next line specifies the dimensions of matrix A:
rows cols
The following lines contain the rows of matrix A.
add
2 2
1 2
3 4
2 2
5 6
7 8
6 8
10 12
multiply
2 3
1 2 3
4 5 6
3 2
7 8
9 10
11 12
scalMultiply
2 2
1 2
3 4
5
Result multiplies the matrix by 5.
transpose
2 3
1 2 3
4 5 6
Output becomes a 3 × 2 matrix.
The program checks for invalid input conditions such as:
- incorrect matrix dimensions
- mismatched sizes for addition
- invalid sizes for multiplication
- non-positive matrix dimensions
- incorrect row lengths
If invalid input is detected, the program:
- Clears
output.txt - Terminates with the message:
Invalid input
- Place your matrix data in
input.txt - Run the program:
python main.py
- Check the result in:
output.txt
Some design decisions used in this implementation:
- Dictionary-based matrix storage instead of lists
- Separate matrix computation module
- File-based I/O instead of console input
- Explicit input validation
These choices make the matrix operations reusable and easier to maintain.
Future improvements could include:
- Command-line input instead of file input
- Support for floating-point matrices
- Additional operations (determinant, inverse, etc.)
- Unit tests for matrix functions
- More efficient data structures (NumPy)
MIT License