0

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?

mabalenk
  • 887
  • 1
  • 8
  • 17
  • 5
    I think your solution is 1) elegant 2) clear. If you are worried about computational time, I am almost sure this is not the bottleneck. "Early optimization is the root of all evil" – Ander Biguri Jul 14 '20 at 14:53
  • 2
    Identity (and generally diagonal) matrix in Octave is internally implemented as a special compact matrix with efficient operations. However these solutions may be slightly more efficient: `B = tril(A,-1); B+=eye(size(A));` or `B = tril(A,-1); B(1:size(A,1)+1:end) = 1;` – rahnema1 Jul 14 '20 at 15:42

0 Answers0