"Python: Create a 2x2 Matrix Class with Addition, Subtraction, and Multiplication (Example Code Included)"
Here is an example implementation of the `Matrix` class in Python that supports addition, subtraction, and multiplication of 2x2 matrices: ```python class Matrix: def __init__(self, a, b, c, d): self.matrix = [[a, b], [c, d]] def __str__(self): return '\n'.join([' '.join(map(str, row)) for row in self.matrix]) def __add__(self, other): result = [[0, 0], [0, 0]] for i in range(2): for j in range(2): result[i][j] = self.matrix[i][j] + other.matrix[i][j] return Matrix(*result[0], *result[1]) def __sub__(self, other): result = [[0, 0], [0, 0]] for i in range(2): for j in range(2): result[i][j] = self.matrix[i][j] - other.matrix[i][j] return Matrix(*result[0], *result[1]) def __mul__(self, other): result = [[0, 0], [0, 0]] for i in range(2): for j in range(2): for k in range(2): result[i][j] += self.matrix[i][k] * other.matrix[k][j] return Matrix(*result[0], *result[1]) # Example usage matrix1 = Matrix(1, 2, 3, 4) matrix2 = Matrix(5, 6, 7, 8) print("Matrix 1:") print(matrix1) print("\nMatrix 2:") print(matrix2) print("\nAddition:") print(matrix1 + matrix2) print("\nSubtraction:") print(matrix1 - matrix2) print("\nMultiplication:") print(matrix1 * matrix2) ``` This will output: ``` Matrix 1: 1 2 3 4 Matrix 2: 5 6 7 8 Addition: 6 8 10 12 Subtraction: -4 -4 -4 -4 Multiplication: 19 22 43 50 ``` ######[AI写代码神器 | 1039点数解答 | 2024-11-16 22:40:55]
- "Python: Create a 2x2 Matrix Class with Addition, Subtraction, and Multiplication (Example Code Included)"(GPT | 1039点数解答 | 2024-11-16 22:40:55)242
- C++实现不使用vector交换矩阵指定两列(字节豆包 | 556点数解答 | 2026-04-25 20:21:57)15
- Java代码:用户、新闻与评论类的定义展示 (字节豆包 | 33点数解答 | 2024-12-13 19:38:40)231
- 代码大变身:从残缺到完整的 Java 代码补充完善! (字节豆包 | 215点数解答 | 2024-12-13 19:41:46)320
- SQL 查询纠错:精准修正排序子句,实现特定数据筛选与排序 (阿里通义 | 262点数解答 | 2024-05-14 11:17:48)358
- Java 代码分析:从结构优势到潜在问题与注意要点(字节豆包 | 698点数解答 | 2025-09-15 10:13:12)157
- Octave实战:多项式求值、矩阵运算及多项式和差积计算代码揭秘(字节豆包 | 450点数解答 | 2025-03-20 19:10:01)234
- "SQL条件判断下的角色数据更新操作揭秘"(GPT | 51点数解答 | 2024-10-22 11:24:35)308
- "Enhanced SQL Script for SRO MMORPG Database: Conditional Updates, Transactions & Logging"(阿里通义 | 969点数解答 | 2024-10-22 11:26:02)390
- C++编程:输入整数判断奇偶与大小并按需输出(字节豆包 | 189点数解答 | 2025-12-13 20:11:55)95
- C++实现:输入整数判断奇偶与大小并输出对应结果(DeepSeek | 123点数解答 | 2025-12-28 14:53:27)67
- 用按键精灵与大漠插件还原CE脚本功能:游戏内存修改全攻略(字节豆包 | 1016点数解答 | 2026-01-21 14:27:19)66