Search code examples
matrixjulialinear-algebradiagonal

Julia - How to efficiently turn to zero the diagonal of a matrix?


In Julia, what would be an efficient way of turning the diagonal of a matrix to zero?


Solution

  • Assuming m is your matrix of size N x N this could be done as:

    setindex!.(Ref(m), 0.0, 1:N, 1:N)
    

    Another option:

    using LinearAlgebra
    m[diagind(m)] .= 0.0
    

    And some performance tests:

    julia> using LinearAlgebra, BenchmarkTools
    
    julia> m=rand(20,20);
    
    julia> @btime setindex!.(Ref($m), 0.0, 1:20, 1:20);
      55.533 ns (1 allocation: 240 bytes)
    
    julia> @btime $m[diagind($m)] .= 0.0;
      75.386 ns (2 allocations: 80 bytes)