How to quickly find number of non-zero elements in sparse matrix rows?
- To: mathgroup at smc.vnet.net
- Subject: [mg56841] How to quickly find number of non-zero elements in sparse matrix rows?
- From: Matt Pharr <matt at pharr.org>
- Date: Sat, 7 May 2005 04:17:07 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
I have a sparse matrix, roughly 200k by 200k, with about .01% of the
entries non zero, represented with SparseArray. I'd like to reasonably
efficiently generate a 200k-long list where each element is the number of
non-zero entries in the corresponding row of the matrix. I haven't been
able to figure out a quick way to do this.
One approach I've tried is the following (using a made up SparseArray of
an identity matrix to illustrate the point):
In[76]:= sa = SparseArray[Table[{i,i}\[Rule]1, {i, 200000}]];
In[77]:= rowLen[sa_, r_] := Length[ArrayRules[Take[sa, {r}]]]-1
However, it's quite slow--about 1/10 of a second for each value computed
(on a 1GHz Mac G4)
In[80]:= Table[rowLen[sa,i], {i,100}] // Timing
Out[80]=
{12.4165 Second,{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}}
I've got to assume that there's an efficient way to do this--does anyone
have any suggestions?
thanks,
-matt
--
Matt Pharr matt at pharr.org <URL:http://graphics.stanford.edu/~mmp>
=======================================================================
In a cruel and evil world, being cynical can allow you to get some
entertainment out of it. --Daniel Waters
- Follow-Ups:
- Re: How to quickly find number of non-zero elements in sparse matrix rows?
- From: Pratik Desai <pdesai1@umbc.edu>
- Re: How to quickly find number of non-zero elements in sparse matrix rows?
- From: Chris Chiasson <chris.chiasson@gmail.com>
- Re: How to quickly find number of non-zero elements in sparse matrix rows?