How to select a specific column in matrices?

37 views (last 30 days)
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!

Accepted Answer

Star Strider
Star Strider on 7 Jun 2021
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 Comments
Star Strider
Star Strider on 7 Jun 2021
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
.

Sign in to comment.

More Answers (1)

Monika Jaskolka
Monika Jaskolka on 7 Jun 2021
Edited: Monika Jaskolka on 7 Jun 2021
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

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!