Hi,
I found that ndarray is the wrong class to use for this purpose. The
vector I created in the example below was just en uninitialised 3D
vector. Arrays cannot be subclassed:

class Vector(np.array):
        pass

returns an error. But using a matrix as base class works:

class Vector(np.matrix):
        def __abs__(self):
                l = np.sqrt(self*self.transpose())
                return(l[0,0])

V1 = Vector([1,2,2])
V2 = Vector([5,0,4])
print abs(V2-2*V1)

prints 5.0, as it should.

It is very crude (no check on dimensions!), but works.

Martijn


On Thu, 2011-09-22 at 23:54 +0200, Martijn wrote:
> Hi,
> I am trying to create an ndarry subclass for vector calculations. The
> result is not what I intent:
> 
> import numpy as np
> 
> class Vector(np.ndarray):
>       def __abs__(self):
>               return(np.sqrt(sum(self**2)))
> 
> V = Vector([1,2,3])
> 
> print np.sqrt(sum(self**2))
> print abs(V)
> 
> I do not understand the docs at http://www.scipy.org/Subclasses but it
> is late now.
> 
> 
> Martijn
> 
> 
> P.S. I know this is not strictly matplotlib related, but since MP uses
> numpy so heavily, I felt free to ask.
> 
> 
> ------------------------------------------------------------------------------
> All the data continuously generated in your IT infrastructure contains a
> definitive record of customers, application performance, security
> threats, fraudulent activity and more. Splunk takes this data and makes
> sense of it. Business sense. IT sense. Common sense.
> http://p.sf.net/sfu/splunk-d2dcopy1
> _______________________________________________
> Matplotlib-users mailing list
> Matplotlib-users@lists.sourceforge.net
> https://lists.sourceforge.net/lists/listinfo/matplotlib-users



------------------------------------------------------------------------------
All of the data generated in your IT infrastructure is seriously valuable.
Why? It contains a definitive record of application performance, security
threats, fraudulent activity, and more. Splunk takes this data and makes
sense of it. IT sense. And common sense.
http://p.sf.net/sfu/splunk-d2dcopy2
_______________________________________________
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users

Reply via email to