The numpy vector class in terms of linear algebra is likely to be numpy.matrix , which is a subclass of numpy.ndarray . It is not cleaner as such, but it makes your code cleaner because algebraic operations are used instead of elementary.
In [77]: a = np.array([1,2]) In [78]: b = np.array([3,3]) In [79]: a*b Out[79]: array([3, 6]) In [80]: np.dot(a,b) Out[80]: 9 In [81]: np.outer(a,b) Out[81]: array([[3, 3], [6, 6]]) In [82]: a = np.matrix(a).T In [83]: b = np.matrix(b) In [84]: b*a Out[84]: matrix([[9]]) In [85]: a*b Out[85]: matrix([[3, 3], [6, 6]])
If you want to create your own, attach it to one of them, for example:
class v2d(np.ndarray): def __abs__(self): return np.linalg.norm(self) def dist(self,other): return np.linalg.norm(self-other) def dot(self, other): return np.dot(self, other)
Which in the simplest case, you can simply do by looking at ndarray as a new class:
In [63]: a = np.array([1,2]).view(v2d) In [64]: b = np.array([3,3]).view(v2d) In [65]: a Out[65]: v2d([1, 2]) In [66]: abs(b) Out[66]: 4.2426406871192848 In [67]: a - b Out[67]: v2d([-2, -1]) In [68]: a*b Out[68]: v2d([3, 6]) In [69]: a*3 Out[69]: v2d([3, 6]) In [70]: a.dist(b) Out[70]: 2.2360679774997898 In [71]: b.dist(a) Out[71]: 2.2360679774997898 In [72]: a.dot(b) Out[72]: 9
The following is information on subclassing ndarray .
askewchan
source share