Created
June 26, 2012 04:45
-
-
Save doobwa/2993335 to your computer and use it in GitHub Desktop.
Sparse matrix multiplication in julia
This file contains 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
# "Fast matrix multiply" written in Julia | |
# | |
# Method below implements the algorithm described in [Gustavson, 1978]: | |
# http://www.cse.iitb.ac.in/graphics/~anand/website/include/papers/matrix/fast_matrix_mul.pdf | |
# | |
# Copyright (C) 2012 Christopher DuBois | |
# | |
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | |
# | |
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | |
# | |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
function matmul{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, B::SparseMatrixCSC{Tv,Ti}) | |
mA, nA = size(A) | |
mB, nB = size(B) | |
if nA != mB; error("mismatched dimensions"); end | |
colptrA = A.colptr; rowvalA = A.rowval; nzvalA = A.nzval | |
colptrB = B.colptr; rowvalB = B.rowval; nzvalB = B.nzval | |
nnzC = length(nzvalA) + length(nzvalB) | |
colptrC = Array(Ti, nB+1) | |
rowvalC = Array(Ti, nnzC) | |
nzvalC = Array(Tv, nnzC) | |
ip = 1 | |
xb = zeros(Ti, mA) | |
x = zeros(Tv, mA) | |
for i in 1:nB | |
colptrC[i] = ip | |
for jp in colptrA[i]:(colptrA[i+1] - 1) | |
j = rowvalA[jp] | |
nzA = nzvalA[jp] | |
for kp in colptrB[j]:(colptrB[j+1] - 1) | |
k = rowvalB[kp] | |
nzB = nzvalB[kp] | |
if xb[k] != i | |
rowvalC[ip] = k | |
ip += 1 | |
xb[k] = i | |
x[k] = nzA * nzB | |
else | |
x[k] += nzA * nzB | |
end | |
end | |
end | |
for vp in colptrC[i]:(ip - 1) | |
nzvalC[vp] = x[rowvalC[vp]] | |
end | |
end | |
colptrC[nB+1] = ip | |
rowvalC = rowvalC[1:(ip-1)] | |
nzvalC = nzvalC[1:(ip-1)] | |
return SparseMatrixCSC(mA,nB,colptrC,rowvalC,nzvalC) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment