I want set the diagonal elements of a matrix as 1, so I use diag()
function, but I got error.
aa=rand(3,3);
diag(aa)=ones(3)
error in method definition: function LinAlg.diag must be explicitly imported to be extended
I also try to use diag(aa)=[1,1,1]
, but it also seems not work.
How can solve this problem.
First of all, diag(aa) = ones(3)
is Matlab syntax and doesn't work as you would think. In Julia, it is a method definition for diag
, which is why you get that error. You have to use indexing using square brackets, as in C-style languages. (And maybe read about the differences from Matlab to avoid future surprises.)
To answer the question, you can use LinearAlgebra.diagind
to get the indices of the diagonal, and assign 1
to them by broadcasting:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With