Sparse matrix with diagonal index

281 views
Skip to first unread message

Amit Jamadagni

unread,
Mar 10, 2015, 2:07:47 PM3/10/15
to julia...@googlegroups.com
Hello,
        I was trying to create a spare matrix with diagonal indexing. I have done the following :
x = [3:-1:3]

When I give in 

julia> spdiagm(x, 0, length(x), length(x))
7x7 sparse matrix with 6 Int64 entries:
[1, 1]  =  3
[2, 2]  =  2
[3, 3]  =  1
[5, 5]  =  -1
[6, 6]  =  -2
[7, 7]  =  -3

it works.

But when I give in 
julia> spdiagm(x, 1, length(x), length(x))
ERROR: BoundsError
 in sparse at sparse/csparse.jl:50
 in spdiagm at sparse/sparsematrix.jl:2133
 in spdiagm at sparse/sparsematrix.jl:2141

I get the above error. Any leads on this would be great. Thanks.

Steven G. Johnson

unread,
Mar 10, 2015, 2:28:39 PM3/10/15
to julia...@googlegroups.com

But when I give in 
julia> spdiagm(x, 1, length(x), length(x))
ERROR: BoundsError
 in sparse at sparse/csparse.jl:50
 in spdiagm at sparse/sparsematrix.jl:2133
 in spdiagm at sparse/sparsematrix.jl:2141

I get the above error. Any leads on this would be great. Thanks.

You need to use length(x)+1.   If you have an MxM matrix, then the k-th diagonal has M-k entries.   You are supplying M entries for the 1st diagonal, which is too many. 

Amit Jamadagni

unread,
Mar 10, 2015, 2:40:24 PM3/10/15
to julia...@googlegroups.com
Thank you very much for the response.
But the behavior of the same in scipy is different i.e., it omits the elements. Is this not the expected behavior ?? The same result is as follows using scipy and numpy :
>>> import numpy as np
>>> import scipy.sparse as sp
>>> m = np.arange(3, -4, -1)
>>> t = sp.spdiags(m,1,len(m),len(m))
>>> t
<7x7 sparse matrix of type '<type 'numpy.int64'>'
        with 6 stored elements (1 diagonals) in DIAgonal format>
>>> t.toarray()
array([[ 0,  2,  0,  0,  0,  0,  0],
       [ 0,  0,  1,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0, -1,  0,  0],
       [ 0,  0,  0,  0,  0, -2,  0],
       [ 0,  0,  0,  0,  0,  0, -3],
       [ 0,  0,  0,  0,  0,  0,  0]])

Steven G. Johnson

unread,
Mar 10, 2015, 3:53:55 PM3/10/15
to julia...@googlegroups.com


On Tuesday, March 10, 2015 at 2:40:24 PM UTC-4, Amit Jamadagni wrote:
Thank you very much for the response.
But the behavior of the same in scipy is different i.e., it omits the elements. Is this not the expected behavior ??

Why would you expect the function to silently ignore some of your inputs? 

Amit Jamadagni

unread,
Mar 10, 2015, 4:14:45 PM3/10/15
to julia...@googlegroups.com
Just was curious why it was not matching with the implementations in python library. I was working on the angular momentum operators and relating stuff from QuTiP which does similar stuff in python. 
Reply all
Reply to author
Forward
0 new messages