Biljana Radovanovic
Biljana Radovanovic

Reputation: 121

How to change values in lower triangular of matrix in julia and transform to upper triangular?

How to change values in lower triangular of matrix in julia and transform to upper triangular? I need help with homework

Upvotes: 0

Views: 667

Answers (1)

Nils Gudat
Nils Gudat

Reputation: 13800

It's still not 100% clear from your discussion in the comments above what you're looking for, but here's an attempt at answering:

julia> using LinearAlgebra

julia> A = [1 2 3; 4 5 6; 7 8 9]
3×3 Array{Int64,2}:
 1  2  3
 4  5  6
 7  8  9

I'll go based on your first comment, indicating you want "tril of the matrix to become triu of the matrix and change values of tril".

As Stefan suggests in his comment, moving the lower triangular values of the matrix to the upper triangular can be accomplished by simply transposing the matrix:

julia> tril(A)
3×3 Array{Int64,2}:
 1  0  0
 4  5  0
 7  8  9

julia> triu(A)
3×3 Array{Int64,2}:
 1  2  3
 0  5  6
 0  0  9

julia> A_tr = A'
3×3 Adjoint{Int64,Array{Int64,2}}:
 1  4  7
 2  5  8
 3  6  9

As you see, A_tr has the values returned by tril(A) in its upper triangular. You can then use @crstnbr's suggestion to replace all the lower triangular values with -3 (adding the minus to make the result visually clearer):

julia> for k in 1:size(A_tr, 1) A_tr[diagind(A_tr, k)] .= -3 end

julia> A_tr
3×3 Adjoint{Int64,Array{Int64,2}}:
 1  -3  -3
 2   5  -3
 3   6   9

Upvotes: 1

Related Questions