Convert portion of matrix under the diagonal to column vector
6 views (last 30 days)
Show older comments
Isabel Nichoson
on 16 Mar 2022
Commented: Isabel Nichoson
on 17 Mar 2022
Hi all,
I currently have a matrix with correlational information that is structured this:
A = [ 1 2 3 4 5
2 1 2 3 4
3 4 1 2 5
4 3 2 1 2
5 4 3 2 1]
I want to turn the portion of the matrix UNDER the diagonal into a vector, i.e. B = [2 3 4 4 3 5 4 3 2]
Hoever, so far the only way of extracting the data under the diagonal I've found so far is the tril(A, -1) function which returns
A = [ 0 0 0 0 0
2 0 0 0 0
3 4 0 0 0
4 3 2 0 0
5 4 3 2 0]
I can turn this into a vector from here but it will include all the extra zeros and I don't want those to be part of the final vector. Does anyone have any suggestions as to the best way to go about this? Thank you so much!
2 Comments
Walter Roberson
on 16 Mar 2022
Perhaps you could make use of squareform() ? However it indexes down instead of across, so it is not directly suitable for your purpose.
Accepted Answer
Stephen23
on 16 Mar 2022
Edited: Stephen23
on 16 Mar 2022
Note that approaches which check if the data are zero (e.g. NONZEROS or ==0) are not robust, because you might have perfectly valid zero-values within that part of the matrix. Here is a more robust approach using indexing:
A = [1,2,3,4,5;2,1,2,3,4;3,4,1,2,5;0,3,2,1,2;5,4,3,2,1] % note the zero!
B = A.';
V = B(tril(true(size(A)),-1).')
1 Comment
More Answers (4)
Davide Masiello
on 16 Mar 2022
A = [ 1 2 3 4 5; 2 1 2 3 4; 3 4 1 2 5; 4 3 2 1 2; 5 4 3 2 1];
A = tril(A,-1)';
A = A(:);
A(A==0) = [];
A = A'
2 Comments
Fangjun Jiang
on 16 Mar 2022
Edited: Fangjun Jiang
on 16 Mar 2022
Golfing... watch for any "holes" under the diagnal line
nonzeros(tril(A,-1)')
2 Comments
Jan
on 16 Mar 2022
Edited: Jan
on 16 Mar 2022
A = [ 1 2 3 4 5; ...
2 1 2 3 4; ...
3 4 1 2 5; ...
0 3 2 1 2; ... % 0 inserted
5 4 3 2 1];
s = size(A);
m = cumsum(diag(ones(1, s(1)-1), -1)) == 1;
C = A(m)
% Or:
s = size(A);
C = A((1:s(1)).' > (1:s(2)))
% In modern Matlab without size():
C = A((1:height(A)).' > (1:width(A)))
0 Comments
Image Analyst
on 16 Mar 2022
I think the easiest way is to just make a mask and use that to extract the values:
A = [ 1 2 3 4 5
2 1 2 3 4
3 4 1 2 5
4 3 2 1 2
5 4 3 2 1]
mask = tril(true(size(A)), -1)
columnVector = A(mask)
Note that this will work regardless if there are zeros in the lower diagonal or not.
0 Comments
See Also
Categories
Find more on Creating and Concatenating 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!