J. Andersen
J. Andersen

Reputation: 1

Minimum within a range of values in a list

I have a list in python that is essentially a list of lists. I would like to find the minimum value within a range of values in that list (i.e. a local minimum). Right now my code looks like

import numpy as np
import matplotlib.pyplot as plt
import os
import pylab as pyl

# create an array from the .txt file. Skip the number of headers of the table so you are left with only numbers in data.
#also each new cross section begins with the line ZONE, comment that out so you are only left wih data points in the array

data = np.genfromtxt('drip2cam1top.txt',comments='ZONE',skip_header=3)


print(data)

print(len(data))
# Generate two vectors x and h from the file. Reshape based on zone I and len(data)/I 
#(size of array,#number of points in a line) and then create two vectors
#divide len(data) by I to get first component and then use I (1808 in this case) for second component. #frames, I
x = np.reshape(data[:,0], [144,1808])
h = np.reshape(data[:,2], [144,1808])

#convert numpy array to a list
h_new = h.tolist()[::10] #every 10th step
x_new = x.tolist()[::10]

#using a trick called list comprehension in the next 4 statements,
#it's for constucting an array in one line
#You can look it up or just ignore it and use the results =)

#position of minima (column)
min_columns = [row.index(min(row)) for row in h_new] #position


#position of minima (row) #of frames is range
min_rows = list(range(144))[::10] #simply every row contains a minimum

#x coordinates of minima
min_coords = [x_new[0][index] for index in min_columns] 

#values of minima
min_values = [min(row) for row in h_new ] 


print(min_values)
print(min_columns)
print(min_rows)
print(min_coords)

#Uncomment the lines below to see the plot
#note the .T in the parameters, it transposes the matrices
#xlim and ylim are chosen based on the data. these can be commented out initially.
plt.xlim([-170,-162])
plt.ylim([-5.0,-4.2])
plt.plot(x[::10].T,h[::10].T)
plt.xlabel('x position (mm)')
plt.ylabel('Surface Height (mm)')
plt.plot(min_coords,min_values, 'ro', ms=3)
plt.title('Horizontal Cross Section of Analog Drip Model ')
plt.show()

This gives me the overall minimum value in each row or 'list'. I wanted to find the minimum between the values of -172 and -162 within each row.

Thanks!

Upvotes: 0

Views: 1242

Answers (1)

jpp
jpp

Reputation: 164813

You can calculate min conditionally via a generator expression:

min_values = [min(i for i in row if -172 <= i <= -162) for row in h_new]

You may wish to supply a default argument for when no in-scope value exists in a row:

min_values = [min((i for i in row if -172 <= i <= -162), default=0) for row in h_new]

Upvotes: 4

Related Questions