How compare two vectors in conditional

Hi, I want to make the comparison between two vectors, it must have the condition that a < 0 and b < 0, this is my code:

a = vec(rand(8,1))
b = vec(rand(8,1))

if a .< 0 && b .< 0 #compare two vector
    a = 0
    b = 1
end

And I get this error:

ERROR: LoadError: TypeError: non-boolean (BitVector) used in boolean context
Stacktrace:
 [1] top-level scope

do you want all(a .< 0)? (or the slightly more efficient all(x->x>0))?

1 Like

Thanks, I did not know this command. This solved my problem.

a = vec(rand(8,1))
b = vec(rand(8,1))

if all(a .> 0) && all(b .> 0) #compare two vector
    global a,b
    a = 0
    b = 1
end

Instead of the above, you can write

a = rand(8)
b = rand(8)

As for the rest of your code,

changing a and b from vectors to scalars, is a bad idea, and will make your code slow and unpredictable. Changing the type in a variable depending on values creates a type instability, and there is no way for the compiler to predict what types of values will be held in those variables.

Global variables should also be avoided, and it is recommended that code should be inside functions.

4 Likes