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

2 views (last 30 days)
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.

Accepted Answer

Scott MacKenzie
Scott MacKenzie on 21 Jun 2021
Edited: Scott MacKenzie on 21 Jun 2021
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 Comments
Jordan
Jordan on 22 Jun 2021
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 on 22 Jun 2021
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

Sign in to comment.

More Answers (0)

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!