[SciPy-user] Shift the rows of a matrix

Robert Kern robert.kern@gmail....
Sun Nov 16 18:49:52 CST 2008

On Fri, Nov 7, 2008 at 03:12, Roger Herikstad <roger.herikstad@gmail.com> wrote:
> Hi list,
>  I was curious if anyone has a good method of shifting individual rows
> of a matrix? My problem is that I have a matrix consisting of
> waveforms on the rows, and I want to shift each waveform, i.e. pad
> with zeros on either end, depending on where the minimum point of each
> waveform is located relative to a pre-determined zero point. For
> example, if each waveform consists for 32 data points, I would be
> interested in aligning each waveform so that the minimum point always
> happens on index 10. My current solution is to loop through each
> waveform and taking the dot product with a shift matrix, but I'd
> rather avoid the for loop if possible. If anyone has any thoughts, I'd
> be happy for any input. Thanks!

You can do this with fancy indexing. Find the minimum index across the rows:

  jmin = x.argmin(axis=1)

Shift this to correspond to row indices in the new array such that the
minimum will be on index 10 (note: I suspect you will need to pad to
at least 2*32 and place the minimum in the center to be safe, but you
know your problem better than I).

  jmin_shift = 10 - jmin

Turn this array into a column vector and add it to arange(32) to
create an index array of the same size as the original array:

  j = jmin_shift[:,np.newaxis] + np.arange(32)

These are row indices. To get the column indices which we will need,
we can use just a column vector of the right size. Broadcasting will
handle the rest:

  i = np.arange(len(x))[:,np.newaxis]

Use these to set the values in the new array:

  y[i,j] = x

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco

More information about the SciPy-user mailing list