Skip to content

Incorrect conversion from band matrix to sparse matrix #482

Open

Description

@andreasvarga

The following illustrates the issue:

julia> sparse(BandedMatrix(1=>1:3))
4×4 SparseMatrixCSC{Int64, Int64} with 4 stored entries:
 0  1  ⋅  ⋅
 ⋅  ⋅  2  ⋅
 ⋅  ⋅  ⋅  3
 ⋅  ⋅  ⋅  ⋅

The expected result is

julia> sparse(Matrix(BandedMatrix(1=>1:3)))
4×4 SparseMatrixCSC{Int64, Int64} with 3 stored entries:
 ⋅  1  ⋅  ⋅
 ⋅  ⋅  2  ⋅
 ⋅  ⋅  ⋅  3
 ⋅  ⋅  ⋅  ⋅

Similarly:

julia> a = BandedMatrix(1=>1:3,-1=>3:5)
4×4 BandedMatrix{Int64} with bandwidths (1, 1):
 0  1  ⋅  ⋅
 3  0  2  ⋅
 ⋅  4  0  3
 ⋅  ⋅  5  0

julia> sparse(a)
4×4 SparseMatrixCSC{Int64, Int64} with 10 stored entries:
 0  1  ⋅  ⋅
 3  0  2  ⋅
 ⋅  4  0  3
 ⋅  ⋅  5  0

julia> sparse(Matrix(a))
4×4 SparseMatrixCSC{Int64, Int64} with 6 stored entries:
 ⋅  1  ⋅  ⋅
 3  ⋅  2  ⋅
 ⋅  4  ⋅  3
 ⋅  ⋅  5  ⋅

Activity

  1. jecs commented on Apr 24, 2026

    @jecs

    It's even worse when bands span more of the matrix. For example,

    julia> A=BandedMatrix(-5=>1:3,-3=>1:5,0=>1:8,3=>1:5,5=>1:3)
    8×8 BandedMatrix{Int64} with bandwidths (5, 5):
     1  0  0  1  0  1  ⋅  ⋅
     0  2  0  0  2  0  2  ⋅
     0  0  3  0  0  3  0  3
     1  0  0  4  0  0  4  0
     0  2  0  0  5  0  0  5
     1  0  3  0  0  6  0  0
     ⋅  2  0  4  0  0  7  0
     ⋅  ⋅  3  0  5  0  0  8
    
    julia> sparse(A)
    8×8 SparseMatrixCSC{Int64, Int64} with 58 stored entries:
     1  0  0  1  0  1  ⋅  ⋅
     0  2  0  0  2  0  2  ⋅
     0  0  3  0  0  3  0  3
     1  0  0  4  0  0  4  0
     0  2  0  0  5  0  0  5
     1  0  3  0  0  6  0  0
     ⋅  2  0  4  0  0  7  0
     ⋅  ⋅  3  0  5  0  0  8
    
    julia> sparse(Matrix(A))
    8×8 SparseMatrixCSC{Int64, Int64} with 24 stored entries:
     1  ⋅  ⋅  1  ⋅  1  ⋅  ⋅
     ⋅  2  ⋅  ⋅  2  ⋅  2  ⋅
     ⋅  ⋅  3  ⋅  ⋅  3  ⋅  3
     1  ⋅  ⋅  4  ⋅  ⋅  4  ⋅
     ⋅  2  ⋅  ⋅  5  ⋅  ⋅  5
     1  ⋅  3  ⋅  ⋅  6  ⋅  ⋅
     ⋅  2  ⋅  4  ⋅  ⋅  7  ⋅
     ⋅  ⋅  3  ⋅  5  ⋅  ⋅  8
    
  2. dlfivefifty commented on Apr 24, 2026

    @dlfivefifty
    Member

    A PR to correct this would be very much appreciated!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions