I have an array of floats, lets say "array=([2.0, 7.0, 8.0, 1.0])", and I need to create a second array that applies a formula (out of two) to the elements of the first based on a "if" statement applied to the respective element on a third array (let`s say, array3 = ([1, 4, 5, 1]) ). Something like "If array3_element is < 3, than array2_element = array_element * 2. If array3_element > 3, than array2_element = array_element * 3". For this example,the result for "array" would be "array2=([4.0, 21.0, 24.0, 2.0])".
The code below is my best attempt, but it doesn`t work as expected. It tests only the first element with the "if" statement and applies the same chosen formula to the role array.
As = np.array ([[20], [20]])
def Rsi (x, curv_adi):
for i in def_aco(x,curv_adi):
if abs(i) > epsilon_aco:
return (As/10000)*(Fsd*1000)
else:
return (As/10000)*(Fsd*1000)*((def_aco(x,curv_adi))/(epsilon_aco))
*def_aco (x, curv_adi) being a function up in the code that results in "def_aco = ([2.3275, 0.1275])" and represents the "array3" on the example above. As is "array" and "array2 would be the function result.
CodePudding user response:
let's translate your code to general terms:
def func(array3):
for i in array3:
if condition:
return array1_element
else:
return array3_element
The problem with the code is, that you will get only the first element, because you return from the function instead of iterate over all the array.
You can fix it by:
array2 = []
for n, i in enumerate(array3):
if <condition>:
array2.append(array[n])
else:
array2.append(array3[n])
If you want, you can use list comprehension instead:
array2 = [array[n] if <condition> else array3[n] for n, i in enumerate(array3)]
So, in your case you can solve it by:
def Rsi (x, curv_adi):
ret = []
for n, i in enumerate(def_aco(x,curv_adi)):
if abs(i) > epsilon_aco:
ret.append((As/10000)*(Fsd*1000))
else:
ret.append((As/10000)*(Fsd*1000)*((def_aco(x,curv_adi))/(epsilon_aco)))
return ret
`