1

I was comparing each value from a matrix (created using NumPy) with the value of a variable. But I keep getting this error:

File "main.py", line 63, in findClusters if(val<=nearest): ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I tried printing out the value and its not an array, but a float value. When I gave all(val), the error is "float is not iterable" Whats wrong with my code?

for i in range(0,count):
    nearest = 99999.99
    for ctr in center:
        val = mtrx.item((ctr,i))
        if(val<=nearest):
            nearest = mtrx[ctr][i]
            centerassign = ctr
4
  • Try with if val.all() <= nearest: Commented Oct 12, 2015 at 3:25
  • Then I get "AttributeError: 'float' object has no attribute 'all'" Commented Oct 12, 2015 at 3:31
  • I ain't a numpy expert, but why do you use simple indexing in nearest = mtrx[ctr][i] and not in val = mtrx.item((ctr,i))? Commented Oct 12, 2015 at 3:32
  • I was using simple indexing at first, but then I though that might be the error when comparing and changed it. I get the same error either way. Commented Oct 12, 2015 at 3:36

1 Answer 1

1

Check val and nearest. One or the other, or both is an array (or numpy matrix). The result of the comparison is then an array - multivalued. But the Python if requires one boolean value.

Look at the Related sidebar for numerous SO questions about the ValueERROr, The truth value ....

Initially nearest is scalar, but on later loops it is set to: mtrx[ctr][i]

Assuming mtrx is np.matrix, beware that indexing operations may still return a 2d array, a matrix.

Use mtrx[ctr,i] if you want to select an item from a matrix. Don't use the sequential brackets ([][]) - unless you clearly understand what they are doing.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried giving all() to both val and nearest and the error becomes - 'float' object has no attribute 'all'. Therefore, both of them must be float objects and not arrays. I then tried printing out the values, and I cannot see any arrays in the output.
Like I said, 1st time around nearest is float; you need to check the 2nd iteration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.