[SciPy-user] matrix construction

Fernando Perez Fernando.Perez at colorado.edu
Fri Sep 24 15:36:30 CDT 2004


Stephen Walton schrieb:
> On Thu, 2004-09-23 at 08:29, William Griffin wrote:
> 
>>I'm trying to build an adjacency matrix (52*52)
> 
> 
> Maybe this is so obvious that I'm missing what you're trying to do:
> 
> from string import *
> from numarray import *
> A=zeros((52,52))			# adjacency matrix
> file=open('data')
> for line in file.readlines():
>    w = split(line)
>    m = atoi(w[0])
>    n = atoi(w[1])
>    A[m, n] += 1

Just a slightly more 'pythonic' approach, for the benefit of the OP (there's 
nothing wrong with your solution, this is just for educational purposes):

import Numeric as N
a=N.zeros((52,52))
for line in open('data'):
     m,n=map(int,line.split())
     a[m,n] += 1

Less temporaries, these days files are their own iterators, the builtin int() 
type does the conversions fine, and string objects have their own split() methods.

This has the advantage of trivially generalizing to arbitrary dimensions if we 
forgo explicit m,n indexing:

dims = 4
size = 52

a = N.zeros((size,)*dims)
for line in open('data'):
     a[map(int,line.split())] += 1


Best,

f



More information about the SciPy-user mailing list