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

2 Ansichten (letzte 30 Tage)
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.

Akzeptierte Antwort

Scott MacKenzie
Scott MacKenzie am 21 Jun. 2021
Bearbeitet: Scott MacKenzie am 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 Kommentare
Jordan
Jordan am 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 am 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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Operating on Diagonal Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by