Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find first row of a matrix <= to a vector

I have a two arrays t1::Array{Float64, 2} and t2::Array{Float64, 2} with the same number of columns. t2 only has one line.

I want to find the first row of t1 which is <= t2 (i.e., the first row i such that t1[i, j] <= t2[1, j] for all j). In the previous version of julia I was using this command:

findfirst(all(t1 .<= t2, 2))

It does not work anymore. The command all(t1 .<= t2, 2) returns the following error:

ERROR: MethodError: objects of type BitArray{2} are not callable
Use square brackets [] for indexing an Array.

Could you tell me how to do it in a more recent version of julia without using for loops? (I am using 1.1.0)

like image 685
Zach Avatar asked Nov 24 '25 04:11

Zach


2 Answers

The syntax for all is now all(A; dims), so you can use all(x .<= y; dims=2) instead:

julia> x = [4 5 6]
1×3 Array{Int64,2}:
 4  5  6

julia> y = [1 2 3; 4 5 6; 7 8 9; 10 11 12]
4×3 Array{Int64,2}:
  1   2   3
  4   5   6
  7   8   9
 10  11  12

julia> all(x .<= y; dims=2)
4×1 BitArray{2}:
 0
 1
 1
 1

However, note that the output of all(x .<= y; dims=2) is a column matrix (not a vector), so if you apply findfirst to it, then findfirst returns a CartesianIndex:

julia> findfirst(all(x .<= y; dims=2))
CartesianIndex(2, 1)

If you want an integer with the row number, you can simply extract the first element of the CartesianIndex:

julia> findfirst(all(x .<= y; dims=2))[1]
2

Alternatively, you could turn the output of all into a vector using vec:

julia> findfirst(vec(all(x .<= y; dims=2)))
2
like image 113
Cameron Bieganek Avatar answered Nov 27 '25 00:11

Cameron Bieganek


I think this will be the closest equivalent

julia> x = [4 5 6]
1×3 Array{Int64,2}:
 4  5  6

julia> y = [1 2 3; 4 5 6; 7 8 9; 10 11 12]
4×3 Array{Int64,2}:
  1   2   3
  4   5   6
  7   8   9
 10  11  12

julia> findfirst(all, collect(eachrow(x .<= y)))
2
like image 20
David Varela Avatar answered Nov 26 '25 23:11

David Varela



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!