Python Forum
Compare each element of an array in a logic statement without using a for loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Compare each element of an array in a logic statement without using a for loop
#1
I want to compare each element of an array to a numerical value without using a for loop. Here's my code:
if rho_phys * np.power(B, eta) <= np.maximum(0, rho_phys - move):
    rho_new = np.maximum(0, rho_phys - move)
elif rho_phys * np.power(B, eta) >= np.minimum(1, rho_phys - move):
    rho_new = np.minimum(1, rho_phys + move)
else:
    rho_new = rho_phys * np.power(B, eta)
rho_phys, B, and rho_new are (9584 x 1) matrices. Eta and move are constants. I originally coded this in MATLAB which understands that I want to take each element and compare them separaely (i.e. element 1 of rho_phys is used with element 1 of B and element 1 of rho_new is populated). But when running this is in Python I get the following error:

Error:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I could use a for loop to compare each value but with the size of my matrices this is extremely inefficient. So my question is, how do I compare each value in the matrices without using a for loop?
Reply


Messages In This Thread
Compare each element of an array in a logic statement without using a for loop - by leocsmith - Mar-31-2021, 11:11 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Elegant way to apply each element of an array to a dataframe? sawtooth500 7 387 Mar-29-2024, 05:51 PM
Last Post: deanhystad
  Loop over an an array of array Chendipeter 1 574 Nov-28-2023, 06:37 PM
Last Post: deanhystad
  Loop through values and compare edroche3rd 6 684 Oct-18-2023, 04:04 PM
Last Post: edroche3rd
Photo Python code: While loop with if statement HAMOUDA 1 573 Sep-18-2023, 11:18 AM
Last Post: deanhystad
  Trying to compare string values in an if statement israelsattleen 1 541 Jul-08-2023, 03:49 PM
Last Post: deanhystad
  Multiply and Addition in the same loop statement with logic. joelraj 2 1,032 Feb-02-2023, 04:33 AM
Last Post: deanhystad
  compare and find the nearest element ? mr_gentle_sausage 4 1,036 Jan-15-2023, 07:11 AM
Last Post: DPaul
  Loop different actions for an array Tibovdv 4 2,755 Mar-25-2021, 06:46 PM
Last Post: jefsummers
Exclamation Compare values in a for loop. penahuse 1 2,366 Feb-22-2021, 07:01 AM
Last Post: buran
  how to create pythonic codes including for loop and if statement? aupres 1 1,922 Jan-02-2021, 06:10 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020