[SciPy-user] Creating a sparse matrix

Nils Wagner nwagner@iam.uni-stuttgart...
Thu Dec 13 08:27:41 CST 2007


On Thu, 13 Dec 2007 14:27:05 +0100
  Robert Cimrman <cimrman3@ntc.zcu.cz> wrote:
> Nils Wagner wrote:
>> On Thu, 13 Dec 2007 14:03:14 +0100
>>   Robert Cimrman <cimrman3@ntc.zcu.cz> wrote:
>>> Nils Wagner wrote:
>>>> Hi all,
>>>>
>>>> How can I build a sparse matrix from the following array 
>>>> ?
>>>>>>> data
>>>> array([['1', '1', '1.7244067583090530E+05'],
>>>>         ['1', '2', '4.7526228631699840E+04'],
>>>> ...
>>>>         ['18', '24', '-1.0245630931609220E+03'],
>>>>         ['24', '24', '4.2234547103090340E+03']],
>>>>        dtype='|S23')
>>>>
>>>> data contains information about row, column and the 
>>>> corresponding entry.
>>>>
>>>> Any pointer would be appreciated.
>>> You read the data from a file, right? 
>> 
>> Exactly.
>> 
>> You should convert
>>> the row/column 
>>> indices to integers and values to floats during the 
>>> reading. 
>> 
>> How can I do that on-the-fly ?
> 
> Well, supposing the file is not too large:
>     fd = open( ... )
>     rows, cols, vals = [], [], []
>     while 1:
>         try:
>             line = fd.readline()
>             if (len( line ) == 0): break
>             if len( line ) == 1: continue
>         except EOFError:
>             break
>         line = line.split()
>         ir, ic, val = int( line[0] ), int( line[1] ), 
>float( line[2] )
>         rows.append( ir )
>         cols.append( ic )
>         vals.append( val )
> 
> Alternatively, you can try to use numpy.fromfile( ..., 
>sep = ' ', dtype 
> = numpy.float64 ) and then reshape it to (n, 3) and 
>re-type the first 
> two columns to ints.
> 
> r.
> _______________________________________________
> SciPy-user mailing list
> SciPy-user@scipy.org
> http://projects.scipy.org/mailman/listinfo/scipy-user
  
Hi Robert,

Thank you very much for your code snippet !
How do I use the COO constructor to build the
matrix from rows, cols and vals ?

Cheers,
             Nils


More information about the SciPy-user mailing list