I want to find the index of the first value in each row of a matrix that satisfies some condition. I want to figure out how to do this without using array comprehensions.
This is how I would do it with an array comprehension:
# let's say we want to find the first column index, per row, where a number in that row is below some threshold.
threshold = 0.5;
data = randn(50,100);
first_threshold_crossings = [findfirst(data[i,:]<threshold) for i in 1:size(data,1)];
Yielding a list of indices that tells you where (column-wise) each row has a value that first drops below the threshold, going from left to right.
Any faster way you can imagine doing this?
Here's how you can do it:
julia> using Random # For RNG reproducability
julia> A = rand(Random.MersenneTwister(0), 3, 3)
3×3 Array{Float64,2}:
0.823648 0.177329 0.0423017
0.910357 0.27888 0.0682693
0.164566 0.203477 0.361828
julia> findfirst.(x < 0.1, eachrow(A))
3-element Array{Union{Nothing, Int64},1}:
3
3
nothing
Note that findfirst
returns nothing
if no index satisfies the condition.