Search code examples
pythonarrayslistquaternionsdimension

How to remove an item from a multi-dimentional array?


In order to make say it simply, I have a list of dimension [32, 31, 4] which I would like to reduce to shape [32, 31, 3] in order to replace every array in the last dimension by an array of size (3).

        for a in range(len(liste)):                #len(list) = 95
        for b in range(len(liste[a])):             #shape = [32, 31, 3], b travels in the 1st dim.
            #print('frame : ', liste[a][b].shape)  #[31, 4]
            #print('b', b)                         #32 frames each time ok              
            for c in range(len(liste[a][b])):      

                #print('c', c)                      #31 each time ok
                #print('norme du quaternion', np.abs(np.linalg.norm(liste[a][b][c]))) #norm = 1      
                r = quat2expmap(liste[a][b][c])   #convertion to expmap successful
                #print('ExpMap : ', r)  

                quat = liste[a][b][c]
                quat = r                #this works

                #print('quat', quat)


                liste[a][b][c] = r      #this doesn't work  

To be more precise, I have a dataset of 95 different gestures each represented by 32 frames and quaternions. I converted the quaternions into ExpMap but due to the difference of shapes I am unable to replace the quaternions by their corresponding ExpMap. The error code I receive the most is the following:

ValueError: could not broadcast input array from shape (3) into shape (4)

It comes from the last line of the code. The weirdest thing is that when I take the quaternion apart and replace it, it works parfectly, yet python would refuse that I do it inside my list. I don't really get why.

Could you lighten me about it? How could I get the proper dimension in my list? I tried all the tricks such as del, remove() but got no result...


Solution

  • You seem to be using numpy arrays (not Python lists). Numpy does not allow changing dimensions on assignment to an element of an array because it would become irregular (some entries with 4 and some with 3).

    Also, iterating through numpy arrays using loops is the wrong way to use numpy. In this case you're probably looking at applying the quat2expmap function to the 4th dimension of your matrix to produce a new matrix of shape (95,32,31,3). This will make maximum use of numpy's parallelism and can be written in a couple of lines without any loops.

    You could either modify the quat2expmap function so that it works directly on your 4d matrix (will be fastest approach) or use np.apply_along_axis (which is not much faster than loops).