Skip to content

Commit

Permalink
Merge pull request JuliaLang#11628 from mauro3/m3/sparse-equal
Browse files Browse the repository at this point in the history
== for sparse matrices
  • Loading branch information
ViralBShah committed Jun 12, 2015
2 parents 064e96b + 896cf04 commit 8908b7e
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
37 changes: 36 additions & 1 deletion base/sparse/sparsematrix.jl
Original file line number Diff line number Diff line change
Expand Up @@ -926,7 +926,42 @@ end
.<{Tv1,Ti1,Tv2,Ti2}(A_1::SparseMatrixCSC{Tv1,Ti1}, A_2::SparseMatrixCSC{Tv2,Ti2}) = broadcast!(<, spzeros( Bool, promote_type(Ti1, Ti2), broadcast_shape(A_1, A_2)...), A_1, A_2)
.!={Tv1,Ti1,Tv2,Ti2}(A_1::SparseMatrixCSC{Tv1,Ti1}, A_2::SparseMatrixCSC{Tv2,Ti2}) = broadcast!(!=, spzeros( Bool, promote_type(Ti1, Ti2), broadcast_shape(A_1, A_2)...), A_1, A_2)


## full equality
function ==(A1::SparseMatrixCSC, A2::SparseMatrixCSC)
size(A1)!=size(A2) && return false
vals1, vals2 = nonzeros(A1), nonzeros(A2)
rows1, rows2 = rowvals(A1), rowvals(A2)
m, n = size(A1)
@inbounds for i = 1:n
nz1,nz2 = nzrange(A1,i), nzrange(A2,i)
j1,j2 = first(nz1), first(nz2)
# step through the rows of both matrices at once:
while j1<=last(nz1) && j2<=last(nz2)
r1,r2 = rows1[j1], rows2[j2]
if r1==r2
vals1[j1]!=vals2[j2] && return false
j1+=1
j2+=1
else
if r1<r2
vals1[j1]!=0 && return false
j1+=1
else
vals2[j2]!=0 && return false
j2+=1
end
end
end
# finish off any left-overs:
for j = j1:last(nz1)
vals1[j]!=0 && return false
end
for j = j2:last(nz2)
vals2[j]!=0 && return false
end
end
return true
end

## Reductions

Expand Down
25 changes: 25 additions & 0 deletions test/sparsedir/sparse.jl
Original file line number Diff line number Diff line change
Expand Up @@ -968,3 +968,28 @@ A[3,1] = 2
A.nzval[2] = 0.0
@test ishermitian(A) == true
@test issym(A) == true

# equality ==
A1 = speye(10)
A2 = speye(10)
nonzeros(A1)[end]=0
@test A1!=A2
nonzeros(A1)[end]=1
@test A1==A2
A1[1:4,end] = 1
@test A1!=A2
nonzeros(A1)[end-4:end-1]=0
@test A1==A2
A2[1:4,end-1] = 1
@test A1!=A2
nonzeros(A2)[end-5:end-2]=0
@test A1==A2
A2[2:3,1] = 1
@test A1!=A2
nonzeros(A2)[2:3]=0
@test A1==A2
A1[2:5,1] = 1
@test A1!=A2
nonzeros(A1)[2:5]=0
@test A1==A2
@test sparse([1,1,0])!=sparse([0,1,1])

0 comments on commit 8908b7e

Please sign in to comment.