[Matrix-SIG] Shifted array ops (was: RE: [Matrix-SIG] QUERY: Array indexing)

Perry Stoll pas@xis.xerox.com
Fri, 12 Mar 1999 10:45:11 -0500


[Tim Peter's continues to dazzle, but stays true to his Buddha-nature by
avoiding a practical solution ;]


What I understand you're asking for is to perform operations on
shifted/rotated versions of big matrices (aka numeric arrays). If that's what
you're after, there is a way to do this sort of thing in NumPy using the
built-in (since Python 1.5, I believe) slice type. The Python deities, in
their glorious munificence, have given us the built-in function slice()
to create slice objects.

The idea is to build up a slice object to represent the particular view of
the data needed and then apply the slice object to the numeric array you
have. The slicing operation doesn't create a copy of the data; it's just a
new view of the original data.

You'll need to learn how slice objects get interpreted by Numeric, but I
don't know where that's documented other than in the source. Does anyone know
if such documetation exists?

As a concrete example, take look at the functions in
  http://starship.python.net/crew/jhauser/NumAdd.py.html

Here's the function to compute a central diffence using this technique:

def diff(m,axis=0):
    """    Foward difference of m along axis axis.    """
    if m.shape[axis] < 2:
        raise 'Error, axis needs at least be of length 2'
    l_sl=[slice(None,None,None)]*len(m.shape)
    u_sl=l_sl[:]
    l_sl[axis]=slice(1,None,1)
    u_sl[axis]=slice(None,-1,1)
    return m[l_sl]-m[u_sl]

Another good place to find this style of index-building is in the
FancyArray.__{get,set}item__ method at
http://starship.skyport.net/~hochberg/FancyArray.py.html

Of course, getting the end-cases right is your job ;)

-Perry