Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matrix of sparse complex numbers in Julia

In Julia, I can create a sparse matrix of zeros:

julia> a = spzeros(2,2)
2x2 sparse matrix with 0 Float64 entries:

julia> a[1,1] = 1
1

julia> full(a)
2x2 Array{Float64,2}:
 1.0  0.0
 0.0  0.0

and I can create a complex matrix:

julia> b = [ 1 ; im ]
2-element Array{Complex{Int64},1}:
 1+0im
 0+1im

If I try assigning a complex value to a sparse matrix of zeros I get an error:

julia> a[1,1] = im
ERROR: InexactError()
 in setindex! at sparse/sparsematrix.jl:1095

which is consistent with the spzeros() returned type being parametrized by Float64:

julia> typeof(a)
SparseMatrixCSC{Float64,Int64} (constructor with 1 method)

How can I create a sparse matrix of complex-typed zeros in Julia?

like image 786
Peeter Joot Avatar asked Mar 18 '23 09:03

Peeter Joot


1 Answers

Looking at what we can pass to spzeros:

julia> methods(spzeros)
# 5 methods for generic function "spzeros":
spzeros(m::Integer,n::Integer) at sparse/sparsematrix.jl:406
spzeros(Tv::Type{T<:Top},m::Integer,n::Integer) at sparse/sparsematrix.jl:407
spzeros(Tv::Type{T<:Top},Ti::Type{T<:Top},m::Integer,n::Integer) at sparse/sparsematrix.jl:409
spzeros(m::Integer) at deprecated.jl:28
spzeros(Tv::Type{T<:Top},m::Integer) at deprecated.jl:28

We see we should be able to pass a type as the first argument:

julia> a = spzeros(Complex{Float64}, 2,2)
2x2 sparse matrix with 0 Complex{Float64} entries:

julia> full(a)
2x2 Array{Complex{Float64},2}:
 0.0+0.0im  0.0+0.0im
 0.0+0.0im  0.0+0.0im

julia> a[1,1] = 2+3.4im
2.0 + 3.4im

julia> a
2x2 sparse matrix with 1 Complex{Float64} entries:
    [1, 1]  =  2.0+3.4im
like image 111
DSM Avatar answered Mar 23 '23 06:03

DSM