How to select a specific column in matrices?

67 次查看(过去 30 天)
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