Julia: Return the entire vector if any of the element in vector is greater than 50

Viewed 125

As I am new to Julia and I am trying to do some exercise

I have a vector

A = [[112.01507313113326, 60.7645449470438, 44.284185340771124, 16.4524736204982]
    [101.46307715025503, 45.051658067785084, 29.896435433335395, 9.8679853915780]]

and I have B=[100,50, 50,100]

I wanted to get A with an entire row if any of the elements is greater than the value of B (in order)

when I use A[A.>B] I am getting only elements that are greater than the B value

Any help would be appreciated.

2 Answers

Assuming that A is (your code is incomplete):

A=[[112.01507313113326, 60.7645449470438, 44.284185340771124, 16.4524736204982] [101.46307715025503, 45.051658067785084, 29.896435433335395, 9.8679853915780]]

You could do something like:

julia> A[:,[any(col .> B) for col in eachcol(A)]]
4×2 Matrix{Float64}:
 112.015   101.463
  60.7645   45.0517
  44.2842   29.8964
  16.4525    9.86799

Since the OP states A is a vector, one can do an array comprehension,

[a for a in A if any(a.>B)]

or a direct indexing using broadcasting,

A[any.(A.>(B,))]

which both give a similar (same) vector:

2-element Vector{Vector{Float64}}:
 [112.01507313113326, 60.7645449470438, 44.284185340771124, 16.4524736204982]
 [101.46307715025503, 45.051658067785084, 29.896435433335395, 9.867985391578]

Surprisingly, the direct indexing with broadcasting is much faster at this short length.

Related