Skip to content

Commit

Permalink
Improve performance of opnorm for (m x 1) and (1 x n) sparse matrices (
Browse files Browse the repository at this point in the history
…#32372)

* Improve performance of opnorm for (m x 1) and (1 x n) sparse matrices

* Restrict values of p to 1, 2, Inf

* Use nzvalview instead of A.nzval
  • Loading branch information
goggle authored and ViralBShah committed Jun 26, 2019
1 parent a7427aa commit d6b6cb5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
13 changes: 10 additions & 3 deletions stdlib/SparseArrays/src/linalg.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1028,9 +1028,16 @@ function opnorm(A::SparseMatrixCSC, p::Real=2)
m, n = size(A)
if m == 0 || n == 0 || isempty(A)
return float(real(zero(eltype(A))))
elseif m == 1 || n == 1
# TODO: compute more efficiently using A.nzval directly
return opnorm(Array(A), p)
elseif m == 1
if p == 1
return norm(nzvalview(A), Inf)
elseif p == 2
return norm(nzvalview(A), 2)
elseif p == Inf
return norm(nzvalview(A), 1)
end
elseif n == 1 && p in (1, 2, Inf)
return norm(nzvalview(A), p)
else
Tnorm = typeof(float(real(zero(eltype(A)))))
Tsum = promote_type(Float64,Tnorm)
Expand Down
14 changes: 14 additions & 0 deletions stdlib/SparseArrays/test/sparse.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1803,6 +1803,20 @@ end
resize!(foo.nzval, 5)
setindex!(foo.nzval, NaN, 5)
@test norm(foo) == 2.0

# Test (m x 1) sparse matrix
colM = sprandn(10, 1, 0.6)
@test opnorm(colM, 1) opnorm(Array(colM), 1)
@test opnorm(colM) opnorm(Array(colM))
@test opnorm(colM, Inf) opnorm(Array(colM), Inf)
@test_throws ArgumentError opnorm(colM, 3)

# Test (1 x n) sparse matrix
rowM = sprandn(1, 10, 0.6)
@test opnorm(rowM, 1) opnorm(Array(rowM), 1)
@test opnorm(rowM) opnorm(Array(rowM))
@test opnorm(rowM, Inf) opnorm(Array(rowM), Inf)
@test_throws ArgumentError opnorm(rowM, 3)
end

@testset "sparse matrix cond" begin
Expand Down

0 comments on commit d6b6cb5

Please sign in to comment.