Created
December 2, 2014 06:55
-
-
Save masquevil/e5c1f64f28caaa9721e8 to your computer and use it in GitHub Desktop.
三元组矩阵乘法
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Multiply(SpareMatrix<T> *a, SpareMatrix<T> *b, SpareMatrix<T> *c){ | |
int sum, ai = 0, tmpai, di = 0, anrow, ancol, dnrow, dncol; | |
SpareMatrix<T> *d = new SpareMatrix<T>; | |
QuickTransMat<T>(b, d); //把b转置变为d | |
c->n = a->n; //c是结果矩阵,结果矩阵为b->m行,a->n列 | |
c->m = b->m; | |
c->t = 0; //初始情况,c内没有非零元素 | |
if (a->n == b->m){ //如果乘法成立 | |
for (int ia = 0; ia < a->m; ia++){ //遍历a的每一行,ai是a的行号 | |
tmpai = ai; //ai初始为0,指向a的第一个非零元素(ai是下标),让tmpai 等于 ai | |
di = 0; //让di从头开始,指向d的第一个非零元素(di是下标) | |
dnrow = d->data[0].row; //dnrow是d第一个非零元素所在的行 | |
dncol = d->data[0].col; //dncol是d第一个非零元素所在的列 | |
for (int id = 0; id < d->m; id++){ //遍历d | |
ai = tmpai; //让ai从头开始,等于 tmpai //因为在遍历的过程中,ai可能会逐渐后移(矩阵乘法是a的某一行与d的每一列相乘,如果a当前行有多个非零元素,那么遍历到第1个元素后,ai就会后移到第2个元素。最后ai就会移动到下一行的第一个元素。因此需要在每次循环开始时将a重置为当前行的第一个非零元素) | |
anrow = a->data[ai].row; //a第ai个非零元素所在的行 | |
ancol = a->data[ai].col; //a第ai个非零元素所在的列 | |
sum = 0; //sum初始化 | |
for (int j = 0; j < a->n; j++){ //遍历每一列 | |
if (anrow == ia && ancol == j && dnrow == id && dncol == j){ //如果遍历到的a的第[ia][j]个元素非零,和d的第[id][j]个非零元素 | |
sum += a->data[ai].value * d->data[di].value; //相乘相加 | |
} | |
if (anrow == ia && ancol == j){ //如果遍历到的a的第[ia][j]个元素非零,则ai后移 | |
ai++; | |
if (ai < a->t){ //如果可以后移则后移 | |
anrow = a->data[ai].row; | |
ancol = a->data[ai].col; | |
} | |
else { //如果不可以后移,则选择一个超出范围的位置。因为a只有m行n列,所以在上一个if的判断中,(anrow == ia && ancol == j)肯定不会成立 | |
anrow = a->m + 1; | |
ancol = a->n + 1; | |
} | |
} | |
if (dnrow == id && dncol == j){ //如果遍历到的d的第[id][j]个元素非零,则di后移 | |
di++; | |
if (di < d->t){ | |
dnrow = d->data[di].row; | |
dncol = d->data[di].col; | |
} | |
else { | |
dnrow = d->m + 1; | |
dncol = d->n + 1; | |
} | |
} | |
} | |
if (sum != 0){ | |
c->data[c->t].value = sum; | |
c->data[c->t].row = ia; | |
c->data[c->t].col = id; | |
c->t++; | |
} | |
} | |
} | |
} | |
else{ | |
cout << "these two matrix can't multiplicate."; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment