Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 298
Davi Barreira Avatar asked Oct 24 '25 19:10

Davi Barreira


1 Answers

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)
like image 92
Przemyslaw Szufel Avatar answered Oct 26 '25 20:10

Przemyslaw Szufel