8
using LinearAlgebra;
        a = rand(4,1);
        B = diagm(a);
        C  = Diagonal(a);

The above code causes an error/(not intended) in creating a diagonal matrix.

if a = [1 2 3 4]

I need a matrix like:

D = [1 0 0 0;0 2 0 0;0 0 3 0;0 0 0 4].

C = Diagonal(a) creates C = [1]

B = diagm(a); gives an error message:

Error messages: ERROR: MethodError: no method matching diagm(::Matrix{Float64})

You might have used a 2d row vector where a 1d column vector was required. Note the difference between 1d column vector [1,2,3] and 2d row vector [1 2 3]. You can convert to a column vector with the vec() function. Closest candidates are: diagm(::Pair{var"#s832", var"#s831"} where {var"#s832"<:Integer, var"#s831"<:(AbstractVector{T} where T)}...) at C:\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.6\LinearAlgebra\src\dense.jl:279 diagm(::Integer, ::Integer, ::Pair{var"#s832", var"#s831"} where {var"#s832"<:Integer, var"#s831"<:(AbstractVector{T} where T)}...) at C:\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.6\LinearAlgebra\src\dense.jl:280 diagm(::AbstractVector{T} where T) at C:\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.6\LinearAlgebra\src\dense.jl:329 ... Stacktrace: [1] top-level scope @ REPL[16]:1

Vinod
  • 4,138
  • 11
  • 49
  • 65
  • 2
    The error message is actually quite good here, and exactly explains the problem and how to solve it: "You might have used a 2d row vector where a 1d column vector was required. Note the difference between 1d column vector [1,2,3] and 2d row vector [1 2 3]. You can convert to a column vector with the vec() function." – DNF Oct 18 '21 at 07:37

1 Answers1

9

I think the problem is your a is matrix.

Try this:

a = [1,2,3,4]  # 4-element Vector{Int64}
C = Diagonal(a)
4×4 Diagonal{Int64, Vector{Int64}}:
 1  ⋅  ⋅  ⋅
 ⋅  2  ⋅  ⋅
 ⋅  ⋅  3  ⋅
 ⋅  ⋅  ⋅  4

Or, to make a true diagonal matrix:

M = diagm(a)
4×4 Matrix{Int64}:
 1  0  0  0
 0  2  0  0
 0  0  3  0
 0  0  0  4
Bill
  • 10,323
  • 10
  • 62
  • 85
  • 1
    Nice tutorial [here](https://web.eecs.umich.edu/~fessler/course/551/julia/tutor/03-diag.html) explaining the various types of diagonal matrix in Julia. – Bill Oct 18 '21 at 03:00
  • 3
    Worth commenting is that the first option by @Bill is not materialized as a `Matrix` so linear algebra operations on it will be much faster (as long a you stick to functions having specific implementation for the `Diagonal` argument) – Przemyslaw Szufel Oct 18 '21 at 11:12
  • @Bill, what is the best way to produce a normalized adjacency matrix in Julia? – Vass Sep 21 '22 at 20:07
  • @Vass I'm not sure. Is this related to this question or is it a different question? – Bill Sep 21 '22 at 22:18
  • @Bill, the diagonal is key in producing normalized adjacency matrices – Vass Sep 21 '22 at 22:50
  • 1
    @Vass I would consider asking a new question if you can't find an answer online. You can always reference this one. – Bill Sep 22 '22 at 03:33