Defining Sparse Matrix from Scratch using vectors

You can also see the Alan Edelman’s video on Matrix Structures for inspiration.

I have written (to learn and for fun) the structure as suggested by Steven and some two other functions, and already matrix multiplications work. This is very nice :slight_smile:

julia> A = Tridiag([1,1],[2,2,2],[3,3])
3Ă—3 Tridiag{Int64}:
 2  3  0
 1  2  3
 0  1  2

julia> A*A
3Ă—3 Array{Int64,2}:
 7  12   9
 4  10  12
 1   4   7

If you want to see what I did so far, here is the code:

Code
julia> struct Tridiag{T<:Number} <: AbstractMatrix{T} 
         a :: Vector{T}
         b :: Vector{T}
         c :: Vector{T}
       end

julia> function Base.getindex(M::Tridiag{T}, i::Int, j::Int) where T
         if i == j
           M.b[i]
         elseif i == j + 1
           M.a[j]
         elseif i == j - 1
           M.c[i]
         else
           zero(T)
         end
       end

julia> Base.size(M::Tridiag) = (length(M.b),length(M.b))

julia> A = Tridiag([1,1],[2,2,2],[3,3])
3Ă—3 Tridiag{Int64}:
 2  3  0
 1  2  3
 0  1  2

julia> A*A
3Ă—3 Array{Int64,2}:
 7  12   9
 4  10  12
 1   4   7
4 Likes