[Numpy-discussion] Distance Formula on an Array
Eike Welk
eike.welk at gmx.net
Sun Apr 26 16:56:08 EDT 2009
Hello Ian!
On Saturday 25 April 2009, Ian Mallett wrote:
> Can I make "vec" an array of class instances? I tried:
> class c:
> def __init__(self):
> self.position = [0,0,0]
> vec = array([c(),c(),c()])
> pos = array([0,4,0])
> sqrt(((vec.position - pos)**2).sum(1))
>
> Which doesn't work. I'm not familiar with class objects in
> arrays--how should they be referenced?
You could use objects that don't store the positions but who know how
to access them. The positions are stored in a Numpy array, the
objects store only the index to the array.
This is similar to the flyweight design pattern. Here is an example
class:
from numpy import array
class MyThing(object):
position_array = array([], 'd')
def __init__(self, index):
self.index = index
def get_position(self):
return MyThing.position_array[self.index]
def set_position(self, new_val):
MyThing.position_array[self.index] = new_val
position = property(get_position, set_position, None,
'Position of MyThing, stored collectively for all objects in '
'MyThing.position_array.')
#--------- Use the MyThig class ------------------------------
#fill the array of positions with data
MyThing.position_array = array([[0,0,0], [0,1,0], [0,0,3]], 'd')
#create instance at index 1
thing1 = MyThing(1)
print thing1.get_position()
print thing1.position
assert (thing1.position == array([0,1,0])).all()
#create instance at index 2
thing2 = MyThing(2)
print thing2.position
assert (thing2.position == array([0,0,3])).all()
thing2.position = array([1,2,3])
print thing2.position
assert (thing2.position == array([1,2,3])).all()
Kind regards,
Eike.
More information about the NumPy-Discussion
mailing list