Check condition on diagonal entries of matrix in Julia?

Viewed 60

In Julia, suppose I have a matrix A, and I would like to know the number of diagonal entries that are smaller than some threshold value. One way to do this is to initialize a new array of diagonal entries of A with diag(), and then use the count function to count how many are below some threshold value.

A_diag=(diag(A))
count(<(0.1), A_diag)

But, I prefer not to initialize any new arrays (as I did with the diag function). Is there any way in Julia to check how many diagonal entries of a matrix satisfy some condition, without initializing any NEW arrays?

1 Answers

You can get this count quite fast without creating a new array for diagonal elements by working directly on the given matrix. Using a generator instead of diag(A) will by 3X faster.

count(<(0.1), A[i,i] for i in minimum(axes(A)))

Comparing the speed of the following variants in Julia 1.9.0-DEV shows a speed advantage of my solution.

A = rand(500,500)
@btime count(<(0.1), diag($A))
@btime count(<(0.1), $A[i] for i in diagind($A))
@btime count(<(0.1), $A[i,i] for i in minimum(axes($A)))
  # 697.931 ns (1 allocation: 4.06 KiB)
  # 495.876 ns (0 allocations: 0 bytes)
  # 213.962 ns (0 allocations: 0 bytes)

In Julia 1.8.0, however, the numbers are more close:

  # 668.387 ns (1 allocation: 4.06 KiB)
  # 345.370 ns (0 allocations: 0 bytes)
  # 317.373 ns (0 allocations: 0 bytes)
Related