# LU Decomposition - return permutation matrix instead of vector

Dear Community,

Is there any way to return in Julia full permutation matrix instead of vector?

using LinearAlgebra
A = [0 4 2; 10 2 1; 1 1 1]
L,U,P = lu(A)

P is returned as [2,1,3].
However, I would like to have in the following form: [0,1,0;1,0,0;0,0,1]

Is there any way to enforce this in Julia?

Thank you in advance for any help

``````
julia> p = [2, 1, 3];

julia> n = length(p);

julia> II = Matrix{Int}(I, n, n)
3Γ3 Array{Int64,2}:
1  0  0
0  1  0
0  0  1

julia> II[p, :]
3Γ3 Array{Int64,2}:
0  1  0
1  0  0
0  0  1
``````
5 Likes

Alternatively you can also use `I(n)` to get the identity matrix.

``````julia> II = Matrix{Int}(I, 3, 3)
3Γ3 Array{Int64,2}:
1  0  0
0  1  0
0  0  1

julia> I(3)
3Γ3 Diagonal{Bool,Array{Bool,1}}:
1  β  β
β  1  β
β  β  1
``````
2 Likes

Except then indexing into it with the vector gives you a sparse matrix which may or may not be what you want / need.

``````julia> I(3)[p, :]
3Γ3 SparseArrays.SparseMatrixCSC{Bool,Int64} with 3 stored entries:
[2, 1]  =  1
[1, 2]  =  1
[3, 3]  =  1
``````

Yeah, I see the issue hereβ¦

Or simply

``````julia> using LinearAlgebra

julia> A = rand(5,5);

julia> lu(A).P
5Γ5 Array{Float64,2}:
0.0  1.0  0.0  0.0  0.0
0.0  0.0  1.0  0.0  0.0
0.0  0.0  0.0  1.0  0.0
0.0  0.0  0.0  0.0  1.0
1.0  0.0  0.0  0.0  0.0
``````
3 Likes

Why is that a Float64 matrix instead of an Int matrix?! The permutation vector is an Int vector.

I wonder if you read the docs of `lu`, since you can get it directly as a property:

``````julia> lu(A).P
3Γ3 Array{Float64,2}:
0.0  1.0  0.0
1.0  0.0  0.0
0.0  0.0  1.0
``````
1 Like