Effacer les filtres
Effacer les filtres

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

2 vues (au cours des 30 derniers jours)
Jordan
Jordan le 21 Juin 2021
Commenté : Scott MacKenzie le 22 Juin 2021
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.

Réponse acceptée

Scott MacKenzie
Scott MacKenzie le 21 Juin 2021
Modifié(e) : Scott MacKenzie le 21 Juin 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 commentaires
Jordan
Jordan le 22 Juin 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 le 22 Juin 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

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Operating on Diagonal Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by