I have a very simple question, I am struggling to find an answer to. I would like to craft (upper or lower) unitriangular and unitrapezoidal matrices in Octave. Is there an efficient and elegant way to achieve that?
Let, A = [1 2 3; 4 5 6; 7 8 9]
. I can obtain upper or lower triangular matrix B
with B = triu(A)
and B = tril(A)
. Consider a lower triangular case B = tril(A)
. To extract the elements below the main diagonal I use B = tril(A,-1)
. That will result in
0 0 0
4 0 0
7 8 0
But how to obtain ones on the main diagonal of B
now? One workaround that I have is generating an identity matrix and adding it to B
:
B = tril(A,-1) + eye(size(A))
1 0 0
4 1 0
7 8 1
But I feel this is suboptimal due to the addition. Is there a better way?