[SOLVED] Python turn hard code into loop that iterates through every element

Issue

I was wondering how I would turn my hardcoding section into a loop? I have a very long array that would require me to iterate through every element, drop it, and apply the functions. but hard coding would take forever. ie. apply functions with everything but the first element then append to list, apply functions with everything but the second element then append to list, and so on

x1 = np.array([1,2,4,6])
y1 = np.array([2,4,6,3])
x2 = np.array([2,4,2,7])
y2 = np.array([2,5,3,4])
x3 = np.array([3,5,4,3])
y3 = np.array([2,6,1,2])
x4 = np.array([6,6,4,7])
y4 = np.array([8,9,8,4])

xs = np.array([x1,x2,x3,x4])
ys = np.array([y1,y2,y3,x4])

linear_r2 = []
quadratic_r2 = []

def linear_func(x, a, b):
    return (a * x) + b

def fit_r2(ydata, yfit):
    residuals = ydata - yfit 
    ss_res = np.sum(residuals**2)
    ss_tot = np.sum((ydata - np.mean(ydata))**2)
    r2 = 1 - (ss_res / ss_tot)
    return r2

#hardcoding
xs_1 = np.delete(xs,0,axis = 1) #deletes 0th element for all arrays
ys_1 = np.delete(ys,0,axis = 1) #deletes 0th element for all arrays
xdata = xs_1[0,:]
ydata = ys_1[0,:]
popt, _ = curve_fit(linear_func, xdata, ydata)
yfit = linear_func(xdata, *popt)
linear_1 = fit_r2(ydata,yfit)
linear_r2.append(linear_1)

xs_2 = np.delete(xs,1,axis = 1) ##deletes 1st element for all arrays
ys_2 = np.delete(ys,1,axis = 1)
xdata = xs_2[0,:]
ydata = ys_2[0,:]
popt, _ = curve_fit(linear_func, xdata, ydata)
yfit = linear_func(xdata, *popt)
linear_2 = fit_r2(ydata,yfit)
linear_r2.append(linear_2)

#and so on

Solution

for ind in range(xs.shape[1]):
    xs_1 = np.delete(xs,ind,axis = 1) #deletes i-th element for all arrays
    ys_1 = np.delete(ys,ind,axis = 1) #deletes i-th element for all arrays

the rest is the same (all under the loop):

xdata = xs_1[0,:]
ydata = ys_1[0,:]
popt, _ = curve_fit(linear_func, xdata, ydata)
yfit = linear_func(xdata, *popt)
linear_1 = fit_r2(ydata,yfit)
linear_r2.append(linear_1)

Answered By – SiP

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *