Two questions related to Linear Algebra:
- I need an identity matrix in some computations. Two ways to achieve this:
julia> Matrix{Integer}(I,3,3)
3×3 Array{Integer,2}:
true 0 0
0 true 0
0 0 true
or
julia> diagm(fill(1,3))
3×3 Array{Int64,2}:
1 0 0
0 1 0
0 0 1
I suspect the first approach is more memory efficient (?), but it looks ugly with the boolean interpretation of 1
. It gets even worse if I create an identity matrix over the Rational
type… (true//true
)
Question 1: what is the preferred method?
- I’m doing some column permutations on a matrix
A
, collected in vectorp
. Thus, the resulting matrix isA[:,cp]
. There is an equivalent permutation matrixP
so thatA*P = A[:,cp]
. (Essentially,P = diagm(fill(1,n))[:,p]
wheren=size(A,2)
).
I now need to do row permutations on another matrix, sayP*B*
. So I need to convert the column permutationcp
vector to a row permutation vectorrp
so thatP*B = B[rp,:]
.
Question 2: Is there a built-in Julia function for doing this conversion from cp
to rp
?
[So far, I’ve done it as follows:
julia> A = rand(-9:9,3,3)
3×3 Array{Int64,2}:
0 4 -3
5 2 -5
-6 7 0
julia> cp = [3,1,2]
3-element Array{Int64,1}:
3
1
2
julia> A1 = A[:,cp]
3×3 Array{Int64,2}:
-3 0 4
-5 5 2
0 -6 7
julia> P = diagm(fill(1,3))[:,cp]
3×3 Array{Int64,2}:
0 1 0
0 0 1
1 0 0
julia> A*P
3×3 Array{Int64,2}:
-3 0 4
-5 5 2
0 -6 7
julia> P*A
3×3 Array{Int64,2}:
5 2 -5
-6 7 0
0 4 -3
julia> rp = P*(1:3)
3-element Array{Int64,1}:
2
3
1
julia> A[rp,:]
3×3 Array{Int64,2}:
5 2 -5
-6 7 0
0 4 -3
So… rp = diagm(fill(1,n))[:,cp]*(1:n)
. But this is perhaps not very efficient? Is there a better way?]