Xia.Song
Xia.Song

Reputation: 426

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

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.

Upvotes: 5

Views: 8455

Answers (1)

phipsgabler
phipsgabler

Reputation: 20950

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

Upvotes: 17

Related Questions