-2

I have the following code:

def tau_r(u):
    return (u_1 < u < u_2) * (T1 - T2) + T2
if __name__ == "__main__":
    figure()
    plot(u, tau_r(u))
    show()

I get the following error when I run it:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I suppose it's because it is seeing u as a list while it should perform the task on each element of the list separately. How can I fix this?

yukashima huksay
  • 5,834
  • 7
  • 45
  • 78
  • Can you just use a list comprehension: `return [(u_1 < v < u_2) ... for v in u]`? Note the `...` is just a placeholder for the rest of your equation and should not be in your code. – Engineero Nov 17 '17 at 15:27
  • Are u_1 and u_2 constants? Should tau_r return T2 if u is not between u_1 and u_2? – bphi Nov 17 '17 at 15:28
  • @miradulo I don't think this is a duplicate, as he seems to *want* the array of element-wise comparisons. – Engineero Nov 17 '17 at 15:28
  • @bphi tau is T1 if u is between u1 and u2 and T2 otherwise. – yukashima huksay Nov 17 '17 at 15:29
  • @Engineero And there's no reason OP cannot get it if they use the solution from the linked duplicate. An approach that dips into element-wise comparison without leveraging NumPy is wasteful. – miradulo Nov 17 '17 at 15:30

1 Answers1

1

You can apply the same function to all elements of a list by using map. It'll return a new list with each returned value from the function.

plot(u, list(map(tau_r, u)))
MatsLindh
  • 49,529
  • 4
  • 53
  • 84