Skip to content

Commit e7b08c8

Browse files
samuelpowellJutho
authored andcommitted
Construct sparse matrix from LinearMap (#17)
* Construct sparse matrix from LinearMap * Add tests * Build CSC directly, improve tests
1 parent d5155c7 commit e7b08c8

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/LinearMaps.jl

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,31 @@ function Base.full(A::LinearMap)
8888
return mat
8989
end
9090

91+
# sparse: create sparse matrix representtion of LinearMap
92+
function Base.sparse(A::LinearMap)
93+
M, N = size(A)
94+
T = eltype(A)
95+
rowind = Int[]
96+
nzval = T[]
97+
colptr = Vector{Int}(N+1)
98+
v = zeros(T, N)
99+
100+
for i = 1:N
101+
v[i] = one(T)
102+
Lv = A*v
103+
js = find(Lv)
104+
colptr[i] = length(nzval)+1
105+
if length(js) > 0
106+
append!(rowind, js)
107+
append!(nzval, Lv[js])
108+
end
109+
v[i] = zero(T)
110+
end
111+
colptr[N+1] = length(nzval)+1
112+
113+
return SparseMatrixCSC(M, N, colptr, rowind, nzval)
114+
end
115+
91116
include("transpose.jl") # transposing linear maps
92117
include("linearcombination.jl") # defining linear combinations of linear maps
93118
include("composition.jl") # composition of linear maps

test/runtests.jl

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,14 @@ M = LinearMap(A)
3636
@test full(M') == A'
3737
@test full(M.') == A.'
3838

39+
# test sparse conversions
40+
@test sparse(M) == sparse(full(M))
41+
42+
B = copy(A)
43+
B[rand(1:length(A), 30)] = 0.
44+
MS = LinearMap(B)
45+
@test sparse(MS) == sparse(full(MS))
46+
3947
# test function map
4048
F = LinearMap(cumsum,2)
4149
@test full(F) == [1. 0.;1. 1.]

0 commit comments

Comments
 (0)