在 Julia 中分配矩阵的对角线值,得到 "error in method definition"

In Julia assign the diagonal values of a matrix, get "error in method definition"

我想将矩阵的对角线元素设置为1,所以我使用了diag()函数,但是我得到了错误。

aa=rand(3,3);
diag(aa)=ones(3)

error in method definition: function LinAlg.diag must be explicitly imported to be extended

我也尝试用diag(aa)=[1,1,1],但是好像也行不通。 怎么解决这个问题。

首先,diag(aa) = ones(3)是Matlab语法,并不像你想象的那样工作。在 Julia 中,它是 diag 的方法定义,这就是您收到该错误的原因。您必须使用方括号来使用索引,就像在 C 风格的语言中一样。 (也许阅读 differences from Matlab 以避免将来出现意外。)

要回答这个问题,你可以使用LinearAlgebra.diagind获取对角线的索引,并通过广播分配给它们1

julia> diagind(aa)
1:4:9

julia> aa[diagind(aa)] .= 1
3-element SubArray{Float64,1,Array{Float64,1},Tuple{StepRange{Int64,Int64}},true}:
 1.0
 1.0
 1.0

julia> aa
3×3 Array{Float64,2}:
 1.0       0.726595  0.195829
 0.37975   1.0       0.882588
 0.604239  0.309412  1.0