Convert portion of matrix under the diagonal to column vector

4 次查看(过去 30 天)
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 个评论
Walter Roberson
Walter Roberson 2022-3-16
Perhaps you could make use of squareform() ? However it indexes down instead of across, so it is not directly suitable for your purpose.

请先登录,再进行评论。

采纳的回答

Stephen23
Stephen23 2022-3-16
编辑:Stephen23 2022-3-16
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!
A = 5×5
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
B = A.';
V = B(tril(true(size(A)),-1).')
V = 10×1
2 3 4 0 3 2 5 4 3 2

更多回答(4 个)

Davide Masiello
Davide Masiello 2022-3-16
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'
A = 1×10
2 3 4 4 3 2 5 4 3 2

Fangjun Jiang
Fangjun Jiang 2022-3-16
编辑:Fangjun Jiang 2022-3-16
Golfing... watch for any "holes" under the diagnal line
nonzeros(tril(A,-1)')

Jan
Jan 2022-3-16
编辑:Jan 2022-3-16
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)))

Image Analyst
Image Analyst 2022-3-16
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.

类别

Help CenterFile Exchange 中查找有关 Sparse Matrices 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by