Dav*_*ira 4 matrix linear-algebra diagonal julia
在 Julia 中,将矩阵对角线变成零的有效方法是什么?
假设m
你的矩阵大小N x N
可以这样完成:
setindex!.(Ref(m), 0.0, 1:N, 1:N)
Run Code Online (Sandbox Code Playgroud)
另外一个选择:
using LinearAlgebra
m[diagind(m)] .= 0.0
Run Code Online (Sandbox Code Playgroud)
以及一些性能测试:
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)
Run Code Online (Sandbox Code Playgroud)