Skip to content

Commit d6b6cb5

Browse files
goggleViralBShah
authored andcommitted
Improve performance of opnorm for (m x 1) and (1 x n) sparse matrices (#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
1 parent a7427aa commit d6b6cb5

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

stdlib/SparseArrays/src/linalg.jl

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1028,9 +1028,16 @@ function opnorm(A::SparseMatrixCSC, p::Real=2)
10281028
m, n = size(A)
10291029
if m == 0 || n == 0 || isempty(A)
10301030
return float(real(zero(eltype(A))))
1031-
elseif m == 1 || n == 1
1032-
# TODO: compute more efficiently using A.nzval directly
1033-
return opnorm(Array(A), p)
1031+
elseif m == 1
1032+
if p == 1
1033+
return norm(nzvalview(A), Inf)
1034+
elseif p == 2
1035+
return norm(nzvalview(A), 2)
1036+
elseif p == Inf
1037+
return norm(nzvalview(A), 1)
1038+
end
1039+
elseif n == 1 && p in (1, 2, Inf)
1040+
return norm(nzvalview(A), p)
10341041
else
10351042
Tnorm = typeof(float(real(zero(eltype(A)))))
10361043
Tsum = promote_type(Float64,Tnorm)

stdlib/SparseArrays/test/sparse.jl

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1803,6 +1803,20 @@ end
18031803
resize!(foo.nzval, 5)
18041804
setindex!(foo.nzval, NaN, 5)
18051805
@test norm(foo) == 2.0
1806+
1807+
# Test (m x 1) sparse matrix
1808+
colM = sprandn(10, 1, 0.6)
1809+
@test opnorm(colM, 1) opnorm(Array(colM), 1)
1810+
@test opnorm(colM) opnorm(Array(colM))
1811+
@test opnorm(colM, Inf) opnorm(Array(colM), Inf)
1812+
@test_throws ArgumentError opnorm(colM, 3)
1813+
1814+
# Test (1 x n) sparse matrix
1815+
rowM = sprandn(1, 10, 0.6)
1816+
@test opnorm(rowM, 1) opnorm(Array(rowM), 1)
1817+
@test opnorm(rowM) opnorm(Array(rowM))
1818+
@test opnorm(rowM, Inf) opnorm(Array(rowM), Inf)
1819+
@test_throws ArgumentError opnorm(rowM, 3)
18061820
end
18071821

18081822
@testset "sparse matrix cond" begin

0 commit comments

Comments
 (0)