Boolean Indexing

I’m a little confused on boolean indexing, I’m trying to do something like this:

test=5.4
res=fill(0,size(test))
res[test .> 5] .=5

The size of test could be one or more, but when test is a size of one I get an error where I can’t access the element.

Any suggestions?

Thanks!

You can’t index a vector with a single Bool, it needs to be a vector of bools, see the docs here:

https://docs.julialang.org/en/v1/manual/arrays/#Logical-indexing

Are you maybe looking for

res = ifelse.(test .> 5, 5, 0)

?

3 Likes

You should also be aware that the size of test is not 1, but

julia> size(test)
()

since res is a scalar and not an array. So therefore, res becomes a zero-dimensional array:

julia> res = fill(0, size(test))
0-dimensional Array{Int64, 0}:
0
3 Likes