How to select a specific column in matrices?

조회 수: 63 (최근 30일)
Ara Guz
Ara Guz 2021년 6월 7일
댓글: Star Strider 2021년 6월 7일
I have four (4x4) matrices A B C D. I need to put all the second colums of the four matrices in another matrix X. I tried using
xdatatemp = xdata(:,[end 2]); X = xdatatemp
but it shows an error. Thank you in advance!

채택된 답변

Star Strider
Star Strider 2021년 6월 7일
Concatenate them, then select the second column of the concatenated matrix —
A = randi(9,4)
A = 4×4
7 1 8 5 2 4 5 3 8 6 1 5 1 8 4 4
B = randi(9,4)
B = 4×4
7 9 2 5 3 8 9 8 1 4 9 1 9 5 9 6
C = randi(9,4)
C = 4×4
5 3 4 2 2 7 7 1 4 8 2 3 2 3 9 9
D = randi(9,4)
D = 4×4
5 1 3 7 8 8 7 5 3 1 1 4 1 7 2 1
ABCD = cat(3,A,B,C,D)
ABCD =
ABCD(:,:,1) = 7 1 8 5 2 4 5 3 8 6 1 5 1 8 4 4 ABCD(:,:,2) = 7 9 2 5 3 8 9 8 1 4 9 1 9 5 9 6 ABCD(:,:,3) = 5 3 4 2 2 7 7 1 4 8 2 3 2 3 9 9 ABCD(:,:,4) = 5 1 3 7 8 8 7 5 3 1 1 4 1 7 2 1
NewMatrix = squeeze(ABCD(:,2,:)) % Elimiinate Singleton Dimensions with 'squeeze'
NewMatrix = 4×4
1 9 3 1 4 8 7 8 6 4 8 1 8 5 3 7
.
  댓글 수: 3
Ara Guz
Ara Guz 2021년 6월 7일
편집: Ara Guz 2021년 6월 7일
how about if i need the second row instead of a column, do i change it as
NewMatrix = squeeze(ABCD(2,:,:))?
Star Strider
Star Strider 2021년 6월 7일
To get the second row simply requires changing the addressing slightly from:
NewMatrix = squeeze(ABCD(:,2,:)) % Elimiinate Singleton Dimensions with 'squeeze'
to:
NewMatrix = squeeze(ABCD(2,:,:)).' % Elimiinate Singleton Dimensions with 'squeeze'
Note the added transposition.
Running tthe code with that change:
A = randi(9,4)
A = 4×4
3 4 4 6 9 7 6 9 4 6 5 1 4 4 8 1
B = randi(9,4)
B = 4×4
7 8 9 7 8 4 3 7 2 9 4 8 2 1 2 9
C = randi(9,4)
C = 4×4
6 9 2 9 7 8 8 9 4 5 8 5 6 3 2 8
D = randi(9,4)
D = 4×4
9 4 8 3 9 9 3 4 6 9 1 6 4 1 2 6
ABCD = cat(3,A,B,C,D)
ABCD =
ABCD(:,:,1) = 3 4 4 6 9 7 6 9 4 6 5 1 4 4 8 1 ABCD(:,:,2) = 7 8 9 7 8 4 3 7 2 9 4 8 2 1 2 9 ABCD(:,:,3) = 6 9 2 9 7 8 8 9 4 5 8 5 6 3 2 8 ABCD(:,:,4) = 9 4 8 3 9 9 3 4 6 9 1 6 4 1 2 6
NewMatrix = squeeze(ABCD(2,:,:)).' % Elimiinate Singleton Dimensions with 'squeeze'
NewMatrix = 4×4
9 7 6 9 8 4 3 7 7 8 8 9 9 9 3 4
.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Monika Jaskolka
Monika Jaskolka 2021년 6월 7일
편집: Monika Jaskolka 2021년 6월 7일
A = ones(4)
A = 4×4
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
B = ones(4)*2
B = 4×4
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
C = ones(4)*3
C = 4×4
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
D = ones(4)*4
D = 4×4
4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
X = [A(:,2), B(:,2), C(:,2), D(:,2)]
X = 4×4
1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by