1.编写用“三元组表”存储稀疏矩阵,进行矩阵处理的程序。 (1.)矩阵转置; (2.)矩阵加
时间: 2024-05-15 09:19:47 浏览: 86
法; (3.)矩阵乘法。
以下是用Python实现的程序:
```python
class Triplet:
def __init__(self, row, col, value):
self.row = row
self.col = col
self.value = value
class SparseMatrix:
def __init__(self, row_num, col_num, data):
self.row_num = row_num
self.col_num = col_num
self.data = data
def transpose(self):
trans_data = []
for i in range(self.col_num):
for j in range(len(self.data)):
if self.data[j].col == i:
trans_data.append(Triplet(self.data[j].col, self.data[j].row, self.data[j].value))
trans_matrix = SparseMatrix(self.col_num, self.row_num, trans_data)
return trans_matrix
def add(self, other):
if self.row_num != other.row_num or self.col_num != other.col_num:
print("The two matrices cannot be added!")
return
else:
result_data = []
self_index = 0
other_index = 0
while self_index < len(self.data) and other_index < len(other.data):
if self.data[self_index].row == other.data[other_index].row and self.data[self_index].col == other.data[other_index].col:
new_value = self.data[self_index].value + other.data[other_index].value
if new_value != 0:
result_data.append(Triplet(self.data[self_index].row, self.data[self_index].col, new_value))
self_index += 1
other_index += 1
elif self.data[self_index].row < other.data[other_index].row or (self.data[self_index].row == other.data[other_index].row and self.data[self_index].col < other.data[other_index].col):
result_data.append(self.data[self_index])
self_index += 1
else:
result_data.append(other.data[other_index])
other_index += 1
while self_index < len(self.data):
result_data.append(self.data[self_index])
self_index += 1
while other_index < len(other.data):
result_data.append(other.data[other_index])
other_index += 1
result_matrix = SparseMatrix(self.row_num, self.col_num, result_data)
return result_matrix
def multiply(self, other):
if self.col_num != other.row_num:
print("The two matrices cannot be multiplied!")
return
else:
trans_other = other.transpose()
result_data = []
for i in range(self.row_num):
row_data = []
for j in range(trans_other.row_num):
value = 0
for k in range(len(self.data)):
if self.data[k].row == i:
for l in range(len(trans_other.data)):
if trans_other.data[l].row == j and self.data[k].col == trans_other.data[l].col:
value += self.data[k].value * trans_other.data[l].value
if value != 0:
row_data.append(Triplet(i, j, value))
result_data += row_data
result_matrix = SparseMatrix(self.row_num, trans_other.row_num, result_data)
return result_matrix
```
其中,Triplet类表示一个三元组,包括三个属性:行、列和值。SparseMatrix类表示一个稀疏矩阵,包括三个属性:行数、列数和数据列表。数据列表中的每个元素都是一个三元组。该程序实现了三个矩阵处理方法:转置、加法和乘法。其中,转置方法返回一个新的稀疏矩阵,加法和乘法方法返回一个新的稀疏矩阵作为结果。如果两个矩阵无法进行加法或乘法运算,则程序会输出相应的错误信息。
阅读全文