[Tutor] Values in matrices
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Tue Oct 19 01:54:14 CEST 2004
On Sun, 17 Oct 2004 CryptoLevel9 at aol.com wrote:
> Lets say you have a N x M matrix initially filled with zeros and you
> need to place a value, lets say V, in some row X and column Y where V,
> X, and Y are all values determined by user input and X and Y are less
> than or equal to N and M respectively. If this is possible, could this
> be done many times for different values of V and different values of X
> and Y without assigning the values V, X, and Y new variable names for
> each new value, possibly using some form of programming loop?
Hello,
Yes, this is possible to do with a for loop. You can use reassignment to
reuse the same variable names over and over. Something like:
for r in rows:
for c in cols:
array[r][c] = some_function_that_depends_on(r, c)
However, if you plan to do more sophisticated matrixy stuff, you may want
to look at the 'numarray' package:
http://www.stsci.edu/resources/software_hardware/numarray
It is not a part of the Standard Library, but is an invaluable module if
you plan to do a lot of matrix manipulation.
For example,
###
>>> import numarray
>>> m = numarray.zeros((5,5))
>>> m
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
###
'numarray' makes it ridiculously easy to set a whole row or column to a
particular value:
###
>>> m[3] = 17
>>> m
array([[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[17, 17, 17, 17, 17],
[ 0, 0, 0, 0, 0]])
>>>
>>>
>>> m[:, 2] = 42
>>> m
array([[ 0, 0, 42, 0, 0],
[ 0, 0, 42, 0, 0],
[ 0, 0, 42, 0, 0],
[17, 17, 42, 17, 17],
[ 0, 0, 42, 0, 0]])
###
So numarray allows us to do a lot, even allowing us to do operations on
whole rows and columns. And we can also create arrays whose row/col
values depend on their row and column:
###
>>> def dist(x, y):
... return ((x-5)**2 + (y-5)**2) ** 0.5
...
>>> numarray.fromfunction(dist, (3, 5))
array([[ 7.07106781, 6.40312424, 5.83095189, 5.38516481, 5.09901951],
[ 6.40312424, 5.65685425, 5. , 4.47213595, 4.12310563],
[ 5.83095189, 5. , 4.24264069, 3.60555128, 3.16227766]])
###
Hope this helps!
More information about the Tutor
mailing list