How do I efficiently iterate through a sparse matrix?

1,351 views
Skip to first unread message

Jérôme Tremblay

unread,
Oct 10, 2013, 4:15:13 PM10/10/13
to sage-s...@googlegroups.com
How do I efficiently iterate through a sparse matrix?

SciPy has matrix.tocoo(), what's the equivalent in Sage?

William Stein

unread,
Oct 10, 2013, 4:22:13 PM10/10/13
to sage-support
I don't ever remember implementing an iterator over the elements of a
sparse matrix. At least you could make the corresponding dict (of only
nonzero entries) and then iterate over that:

a = matrix(QQ,1000,sparse=True); a[0,5] = 10; a[10,15] = 2/3

for x, y in a.dict().iteritems():
print x, y

-- William
Reply all
Reply to author
Forward
0 new messages