0

I am looking for an efficient way to find the maximum value and corresponding index along the first axis of a 3D array using Numpy.

Context: I am working with data stored in a 3D array z.shape() = (t, x, y) and have taken a Fourier transform along the t axis using

spectrum = np.fft.fft(z, axis=0)
spectrum.shape(f, x, y)

Here, f is the frequency space, having the same size as t.

I need to construct an array peak_vals.shape() = (x, y) which holds the highest value of the transformed data for each x- and y-coordinate. Moreover, I need to store the frequency corresponding to each peak: peak_freqs.shape() = (x, y)

I already have a function that computes the frequencies corresponding to the Fourier transform:

def freq_arr(t):
    """Determine the frequency space that a DFT of vector t would have"""
    samp_freq = 1/(t[1]-t[0])
    return np.arange(len(t)) * samp_freq / len(t)

To find the peak along the f axis, I came up with:

peak_vals = np.amax(spectrum, axis=0)

How can I find the frequency corresponding to these peaks? I would like to construct a function

def peaks(freqs, spectrum):
    peak_vals = np.amax(spectrum, axis=0)
    # do something
    return peak_vals, peak_freqs

I want to avoid for-loops since I will be working with large arrays.

1
  • np.argmax returns the index where np.amax occurs. Commented Feb 15, 2019 at 22:35

1 Answer 1

1
def peaks(freqs, spectrum):
    peak_vals = np.amax(spectrum, axis=0)

    # get the indices with the max value
    peak_idx = np.argmax(spectrum, axis=0)

    # now use the indices to get the corresponding frequencies
    # peak_freqs is now 2d even though freqs is 1d
    peak_freqs = freqs[peak_idx]

    return peak_vals, peak_freqs
Sign up to request clarification or add additional context in comments.

3 Comments

freqs is a 1D-array, since it is just a transformed time axis., so in can't be unpacked into f, x, y. I also don't fully understand the flatten() part.
Sorry, my bad. I must have overread that the freqs is just a 1D-array. Then the problem becomes even simpler, without using the flatten part.
Indeed seems to do the trick. Thank you. I wasn't aware of this manner of passing indices.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.