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
#2
Your problem is not the comparison, it is the result of the comparison. When you compare two numpy arrays the result is an array of bool, not True or False
import numpy as np

a = np.array([1, 2, 3])
b = np.array([2, 3, 4])
print(a < b)

if a < b:
    print('True')
Output:
[ True True True] Traceback (most recent call last): File "c:/Users/hystadd/Documents/python/sandbox/junk.py", line 7, in <module> if a < b: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
The comparison worked fine, producing an array [ True True True]. This is very similar to what happens when you compare arrays in MATLAB (just replace True/False with 1/0). The problem is converting an array of bool to True or False. The error message tells you how to do this.
import numpy as np

a = np.array([1, 2, 3])
b = np.array([2, 3, 4])
print(a < b)

if all(a < b):
    print('True')
Reply
#3
But I don't want to check if all or any elements satisfy the logic statement. I want to look at each element individually and change its value based on how it responds to the logic statement. Some elements might satisfy the first part of the if statement, some the second etc. So I don't see how all() or any () helps me with this.
Reply
#4
I do not understand.

If I have an array a = np.array([1, 2, 3, 4]) I can compare it to another array b = np.array(4, 3, 2, 1).
a <= b == array([ True, True, False, False]). This does an element by element comparison.

I can compare an NxM array to a constant.
a < 3 == [ True, True, False, False]

As far as I can tell, this is exactly what MATLAB does except it uses 0 and 1 instead of True and False.

I thought your problem was that you were trying to use the result of the comparison as the expression for an if statement. An if statement must resolve to True or False. Python cannot look at an array of boolean, like [ True, True, False, False] and decide if this is True or False, it needs some help. This is where "any" or "all" come in. any(array) is True if any element in the array evaluates to True. all(array) is True if all elements in the array evaluate to True.

If you just want to make an array composed of the smaller value value of two other arrays, use array.minimum the way you are currently using array.maxiumum.
np.minimum(a, b) = [1, 2, 2, 1]

If you want something else you need to explain it in a way others can understand. Either provide some working MATLAB code, or show how you think you have to expand it using for loops in Python, or provide a more detailed description. I suggest the Python code, this being a Python forum.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Elegant way to apply each element of an array to a dataframe? sawtooth500 4 129 3 hours ago
Last Post: sawtooth500
  Loop over an an array of array Chendipeter 1 526 Nov-28-2023, 06:37 PM
Last Post: deanhystad
  Loop through values and compare edroche3rd 6 627 Oct-18-2023, 04:04 PM
Last Post: edroche3rd
Photo Python code: While loop with if statement HAMOUDA 1 535 Sep-18-2023, 11:18 AM
Last Post: deanhystad
  Trying to compare string values in an if statement israelsattleen 1 519 Jul-08-2023, 03:49 PM
Last Post: deanhystad
  Multiply and Addition in the same loop statement with logic. joelraj 2 998 Feb-02-2023, 04:33 AM
Last Post: deanhystad
  compare and find the nearest element ? mr_gentle_sausage 4 1,003 Jan-15-2023, 07:11 AM
Last Post: DPaul
  Loop different actions for an array Tibovdv 4 2,703 Mar-25-2021, 06:46 PM
Last Post: jefsummers
Exclamation Compare values in a for loop. penahuse 1 2,336 Feb-22-2021, 07:01 AM
Last Post: buran
  how to create pythonic codes including for loop and if statement? aupres 1 1,886 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