Convert values upper triangular matrix into vector

140 views (last 30 days)
Hi all,
Imagine a matrix of the following form:
1 2 3 4 5
0 4 6 8 10
0 0 9 12 15
0 0 0 16 20
0 0 0 0 25
Now i do like to obtain a vector with only the values of the upper triangular matrix. in other words a vector of underneath form.
[1 2 3 4 5 4 6 8 10 9 12 15 16 20 25]
What is the best way to obtain this vector?
Thanks in advance
  2 Comments
Fathima Bareeda
Fathima Bareeda on 5 Jun 2021
What is the best way to obtain vector in the form of diagonal elements first and then upper triangular elements..
For eg:[1 4 9 16 25 2 3 4 5 6 8 10 12 15 20]
Walter Roberson
Walter Roberson on 5 Jun 2021
M = [ 1 2 3 4 5
0 4 6 8 10
0 0 9 12 15
0 0 0 16 20
0 0 0 0 25
]
M = 5×5
1 2 3 4 5 0 4 6 8 10 0 0 9 12 15 0 0 0 16 20 0 0 0 0 25
D = diag(M);
eg = [D.', squareform((M-diag(D)).')]
eg = 1×15
1 4 9 16 25 2 3 4 5 6 8 10 12 15 20

Sign in to comment.

Accepted Answer

Jan
Jan on 14 May 2019
Edited: Jan on 17 May 2019
At = A.';
m = tril(true(size(At)));
v = At(m).'
Maybe this is faster (>=R2016b due to auto-expanding):
At = A.';
m = (1:size(At,1)).' >= (1:size(At,2));
v = At(m);
  4 Comments
Lucas Bezerra
Lucas Bezerra on 25 May 2021
It becomes even simpler if you use the triu function instead:
m = triu(true(size(A)));
v = A(m)
Jan
Jan on 25 May 2021
@Lucas Bezerra: The replies the elements in the wrong order [1 2 4 3 6 9 4 8 12 16 5 10 15 20 25].' instead of the wanted [1 2 3 4 5 4 6 8 10 9 12 15 16 20 25] .

Sign in to comment.

More Answers (1)

gb
gb on 30 Jul 2022
Edited: gb on 30 Jul 2022
A = [1 , 2, 3, 4, 5;
0, 4 , 6 , 8 , 10;
0, 0 , 9 , 12 , 15;
0, 0 , 0 , 16 , 20;
0, 0 , 0 , 0 , 25;]
A = 5×5
1 2 3 4 5 0 4 6 8 10 0 0 9 12 15 0 0 0 16 20 0 0 0 0 25
At = A';
m = tril(true(size(A)));
v = At(m)
v = 15×1
1 2 3 4 5 4 6 8 10 9

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!