Search code examples
matlabjuliasparse-matrixdiagonal

Converting a complex vector to a sparse diagonal array in Julia


Trying to replicate a calculation from Matlab in Julia but am having trouble converting a single column complex array into a sparse diagonalized array for matrix multiplication.

Here is the Matlab code I am trying to replicate in Julia:

x*diag(sparse(y)) 

where x is of size 60,600000 and is of type: double, and y is size 600000,1 and is of type: complex double.


Solution

  • You can use Diagonal for that:

    using LinearAlgebra
    x=rand(6,60)
    y=rand(Complex{Float64},60,1)
    x*Diagonal(view(y,:))
    

    I have used view(y,:) to convert y to a Vector - this is here a dimension drop operator you can also use shorter form vec(y) instead. Depending on what you want to do you might explicitly say that you want first column by view(y,:,1).

    Note that Diagonal is just a sparse representation of a matrix.

    julia> Diagonal(1:4)
    4×4 Diagonal{Int64,UnitRange{Int64}}:
     1  ⋅  ⋅  ⋅
     ⋅  2  ⋅  ⋅
     ⋅  ⋅  3  ⋅
     ⋅  ⋅  ⋅  4
    

    Another option that might cover more use case scenarios are BandedMatrices:

    using BandedMatrices
    x*BandedMatrix(0=>view(y,:))
    

    Note that BandedMatrix uses set of pairs for bands, where band 0 is actually the diagonal.