필터 지우기
필터 지우기

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

조회 수: 2 (최근 30일)
Jordan
Jordan 2021년 6월 21일
댓글: Scott MacKenzie 2021년 6월 22일
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