I am migrating some of my code from MATLAB. I was wondering if a functionality exists where I define a certain class (3d vector) and I could define arrays (or lists?) of this class. I would like to be able to use slicing operations on this array.
For example, MATLAB has this functionality:
obj = class(s,'class_name')
creates an array of class class_name objects using the struct s
as a pattern to determine the size of obj.
I understand that numpy offers everything I need for array operations. I am trying to learn right now and this is just and example. So, I would like to do this without numpy arrays.
I might be completely wrong in approaching it this way, so please feel free to suggest if there are any better methods out there to do this. I was looking into subclassing ndarray, but that seems like I would just be creating an array again. Any suggestions are greatly appreciated.
My code so far:
class vector3d(object):
def __init__(self,*args):
nargs = len(args);
if(nargs == 0): # Null Vector
self.x = None; self.y = None; self.z = None;
elif(nargs==1):
if (type(args[0]) is vector3d):
self = args[0];
elif(type(args[0]) is np.ndarray):
Vec = args[0];
if (np.shape(Vec)[0]==1 or np.shape(Vec)[1]==1):
if (np.shape(Vec) == (3,1)):
self.x = Vec[0,0]; self.y = Vec[1,0];
self.z = Vec[2,0];
elif (np.shape(Vec) == (1,3)):
self.x = Vec[0,0]; self.y = Vec[0,1];
self.z = Vec[0,2];
else:
raise Exception('Wrong Type of Inputs');
else:
raise Exception('Wrong Type of Inputs');
VecArray = np.ndarray((10,), dtype=np.object);
print np.shape(VecArray);
for i in range(10):
print i;
VecArray[i] = vector3d(np.random.rand(3,1));
After running the code, when I try the following:
>>> VecArray[1].x
>>> 0.36923808713820772
>>> VecArray[1:5].x
AttributeError Traceback (most recent call last)
<ipython-input-92-899463ad0461> in <module>()
----> 1 VecArray[1:5].x
AttributeError: 'numpy.ndarray' object has no attribute 'x'
I understand that I could make lists of the object. I should have been more specific. I would like to get an indexable variable as output. For example, something that does not give the above as error.