我是靠谱客的博主 淡定小懒虫,这篇文章主要介绍矩阵加法,现在分享给大家,希望可以做个参考。

题目:

实现三元组表示的两个稀疏矩阵的加法。相关定义如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#define MAXSIZE 100 //假设非零元个数的最大值为100 typedef struct { int i,j; //非零元的行下标和列下标,i 和 j 从 1 开始计数,与数学中矩阵元素的编号一致 ElemType e; //非零元的值 }Triple; typedef struct { Triple data[MAXSIZE]; // 非零元三元组表 int m, n, len; // 矩阵的行数、列数和非零元个数 }TSMatrix;

在三元组中,i 和 j 从 1 开始计数,与数学中矩阵元素的编号一致
矩阵加法函数的原型为:

复制代码
1
bool add_matrix(const TSMatrix *pM, const TSMatrix *pN, TSMatrix *pQ);

pM, pN, pQ 分别指向三个矩阵,当 pM 和 pN 两个矩阵不可加时,函数返回 false,否则函数返回 true,且 pQ 指向两个矩阵的和

代码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include "tsmatrix.h" #include <stdio.h> #include <stdlib.h> bool add_matrix(const TSMatrix* pM, const TSMatrix* pN, TSMatrix* pQ) { if (pM->m != pN->m || pM->n != pN->n) { return false; } int i, j, tot = 0; int temp[MAXSIZE + 1][MAXSIZE + 1] = { 0 }; for (i = 0; i < pM->len; i++) { temp[pM->data[i].i][pM->data[i].j] += pM->data[i].e; } for (i = 0; i < pN->len; i++) { temp[pN->data[i].i][pN->data[i].j] += pN->data[i].e; } for (i = 1; i <= pM->m; i++) { for (j = 1; j <= pM->n; j++) { if (temp[i][j] != 0) { pQ->data[tot++].e = temp[i][j]; pQ->data[tot - 1].i = i; pQ->data[tot - 1].j = j; } } } pQ->len = tot; return true; }

最后

以上就是淡定小懒虫最近收集整理的关于矩阵加法的全部内容,更多相关矩阵加法内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(90)

评论列表共有 0 条评论

立即
投稿
返回
顶部