Given two sparse matrices A and B, return the result of AB.
You may assume that A's column number is equal to B's row number.
Example:
A = [ [ 1, 0, 0], [-1, 0, 3] ] B = [ [ 7, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 1 ] ] | 1 0 0 | | 7 0 0 | | 7 0 0 | AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 | | 0 0 1 |使用传统的矩阵相乘的算法肯定会处理大量的0乘0的无用功,所以我们适当的优化算法,我们知道一个 i x k 的矩阵A乘以一个 k x j 的矩阵B会得到一个 i x j 大小的矩阵C,那么我们来看结果矩阵中的某个元素C[i][j]是怎么来的,起始是A[i][0]*B[0][j] + A[i][1]*B[1][j] + ... + A[i][k]*B[k][j],那么为了不重复计算0乘0,我们首先遍历A数组,要确保A[i][k]不为0,才继续计算,然后我们遍历B矩阵的第k行,如果B[K][J]不为0,我们累加结果矩阵res[i][j] += A[i][k] * B[k][j]; 这样我们就能高效的算出稀疏矩阵的乘法,参见代码如下:
# -*- coding: utf-8 -*- """ Created on Sun Sep 02 15:10:34 2018 @author: Administrator """ def SparseMatrixMultiply(A, B):#减少计算次数 res = [[0 for i in range(len(B[0]))] for j in range(len(A))] for i in range(len(A)): for j in range(len(A[0])): if A[i][j] != 0:#non-zero for k in range(len(B[0])): if B[j][k] != 0:#non-zero res[i][k] += A[i][j] * B[j][k] return res if __name__ == '__main__': A = [[1,0,0],[-1,0,3]] B = [[7,0,0],[0,0,0],[0,0,1]] result = SparseMatrixMultiply(A, B) print(result)typedef struct NODE{ //定义稀疏矩阵结点 int i; //行 int j; //列 int data; //值 } Node; typedef struct MATRIX{ //定义稀疏矩阵(可以快速访问) int mu, nu, tu; // mu为矩阵行数,nu为矩阵列数,tu为矩阵中非零元素的个数 Node matrix[MAXSIZE+1]; int rpos[MAXR+1]; } Matrix;
算法时间复杂度为:O(A->tu*B->tu/B->mu)
此外还有十字链表法。
Python科学计算包scipy
import scipy as sp
a = sp.sparse.linalg.norm(S, 'fro')
转载于:https://www.cnblogs.com/AcceptedLin/p/9778834.html
相关资源:python稀疏矩阵乘法