1

I just started to learn Numpy (and Scipy). I wrote a program to compute plot points for an f(x) function. (f(x) can't be given explicitly as I have to numerically solve an equation for each point.) I put the values in a 2D array:

[[x1,    x2,    x3,    ...],
 [f(x1), f(x2), f(x3), ...]]

My aim is now to find the maxima of the f(x) function, and get both it's location xm and it's value f(xm). Of course I could easily do this, but this seems to be something NumPy surely has a simple function. The only thing I found is numpy.amax, but it only returns the maximum value at each axis. (e.g. numpy.amax([[1, 3, 2],[5, 7, 9]], axis=1) returns [3, 9].).

I have two questions:

  1. Did I took the good approach on storing the data points, or is there a specific object in NumPy/SciPy to do this?

  2. Is there a built-in NumPy/SciPy function to find the maxima of my dataset?

    This is the part of the code in question:

    def get_max(args):
        ti_0 = sp.pi / 2.0 + 1E-10
        ti_max = sp.pi - 1E-10
        iters = 10000
    
        step = (ti_max - ti_0) / iters
        ti = ti_0
        result = np.empty((2, iters), float_)   #the dataset, aim is to find the point where ret_energy is maximal
        for i in range(0, iters):
            tret = find_return_time(x, ti)
            ret_energy = ekin(tret, ti)
            ret_time = tret / sp.pi
            result[i, 0] = ret_time
            result[i, 1] = ret_energy
            ti += step
    
        emax = None
        #emax = find_maximal_return_energy(result) #-> ???
        return emax
    

2 Answers 2

3

You can use the argmax function:

data = np.array([[2, 4, 6, 8],[1, 3, 9, 7]])
x = data[0,:]
f = data[1,:]
i = np.argmax(f)
print x[i], f[i]

prints (6,9) as the (x, f(x)) pair with the largest value of f(x). Note that argmax returns only the first occurrence of the maximum value. If there is a possibility that the maximum value of f occurs multiple times and you want all values of x, then you could do

maxvalue = np.max(f)
print x[f == maxvalue], maxvalue
Sign up to request clarification or add additional context in comments.

2 Comments

Out of interest: why is data[1,:] preferred over data[1]?
In this case it doesn't make a difference; it is just a habit of mine. I often have (x,y) data stored in the transpose format, and then I have to write data[:,1] to get the y values.
1

1 - I think so

2 - argmax returns the index for the max value so you can retrieve that value and its corresponding x value.

idx = result[1].argmax()
xm = result[0,idx]
fxm = result[1,idx] 

Comments

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.