Read elements on one side of matrix diagonal into a 1D array

2 次查看(过去 30 天)
I would like to read a 2D nxn matrix into a 1D array with only one column. I would like only values on one side of the matrix's diagonal to be put into the resulting array. For example, if there are rows A-D, and columns 1-4 the resulting 1D array would be:
A2
A3
A4
B3
B4
C4
Is there a straightforward way of achieving this? Thank you.

采纳的回答

Scott MacKenzie
Scott MacKenzie 2021-6-21
编辑:Scott MacKenzie 2021-6-21
There might be a tighter solution, but I think this achieves what you are after:
a = magic(4)
b = a';
c = logical(triu(ones(4),1));
d = b(c')
Output:
a =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
d =
2
3
13
10
8
12
  2 个评论
Jordan
Jordan 2021-6-22
Is this solution also applicable to many different matrices stacked in the z-direction of a 3D array? Then converting the 3D array to a 2D array but doing so with this same process on each individual matrix composing the 3D array? Thank you so much!
Scott MacKenzie
Scott MacKenzie 2021-6-22
The solution is inherently 2D. But, of course, it would work fine in other contexts, such as on a flattened 3D matrix or on individual 2D layers along any dimension of an nD matrix. It will also work, a minor tweak, on rectangular matricies, for example
a = [0 1 2 3 4; 5 6 7 8 9; 4 3 2 1 0]
b = a';
c = logical(triu(ones(size(a)),1));
d = b(c')
Output:
a =
0 1 2 3 4
5 6 7 8 9
4 3 2 1 0
d =
1
2
3
4
7
8
9
1
0

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by