稀疏矩阵A和B,其行数和列数对应相等,编写一个程序,计算A和B之和,假设稀疏矩阵采用三元组表示

如题,矩阵A,B支持自定义行列数,自行输入

#include 
    
    
     
     
#include 
     
     
      
      

typedef struct
{
    int data[50][50];
    int m,n;
} matrix;
typedef int spmatrix[100][3];

void init(matrix *A,matrix *B)
{
    int i,j;
    printf("请输入稀疏矩阵A和B的行数 列数:");
    scanf("%d %d",&A->m,&A->n);
    B->m=A->m;
    B->n=A->n;
    for(i=0; i
      
      
       
       m; i++)
    {
        printf("请输入A矩阵第%d行元素\n",i+1);
        for(j=0; j
       
       
        
        n; j++)
        {
            scanf("%d",&A->data[i][j]);
        }
    }
    for(i=0; i
        
        
          m; i++) { printf("请输入B矩阵第%d行元素\n",i+1); for(j=0; j 
         
           n; j++) { scanf("%d",&B->data[i][j]); } } } void compressmatrix(matrix A,spmatrix C) { int i,j,k=1; for(i=0; i 
          
            D[j][1])//同上,第二种情况 { CD[m][2]=D[j][2]; CD[m][0]=D[j][0]; CD[m][1]=D[j][1]; k++; j++; } else if(C[i][0] 
            
           
          
        
       
       
      
      
     
     
    
    

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个用 Python 实现稀疏矩阵三元组表示程序,包括矩阵加法操作: ```python class SparseMatrix: def __init__(self, data, row, col): self.data = data self.row = row self.col = col def add(self, other): if self.row != other.row or self.col != other.col: raise ValueError("Matrices have different shapes") result_data = [] self_index = other_index = 0 while self_index < len(self.data) and other_index < len(other.data): self_row, self_col, self_val = self.data[self_index] other_row, other_col, other_val = other.data[other_index] if self_row < other_row or (self_row == other_row and self_col < other_col): result_data.append((self_row, self_col, self_val)) self_index += 1 elif self_row > other_row or (self_row == other_row and self_col > other_col): result_data.append((other_row, other_col, other_val)) other_index += 1 else: result_data.append((self_row, self_col, self_val + other_val)) self_index += 1 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 return SparseMatrix(result_data, self.row, self.col) ``` 其中,`data` 是一个存储非零元素的列表,每个元素是一个三元组 `(row, col, val)`,表示矩阵中第 `row` 行、第 `col` 列的元素值为 `val`。`row` 和 `col` 分别表示矩阵的行数和列数。`add` 方法用于将两个稀疏矩阵相加,返回一个新的稀疏矩阵对象。 在使用时,需要先将原始矩阵转换为稀疏矩阵对象,然后调用 `add` 方法进行相加操作,最后可以将结果转换为原始矩阵格式进行输出。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值