How to combine two vectors column-by-column?

조회 수: 17 (최근 30일)
Jake
Jake 2023년 3월 14일
댓글: Stephen23 2023년 3월 17일
I have two matrices, A and B.
A = [1,3,5,7,9,11,13,15]
A = 1×8
1 3 5 7 9 11 13 15
B = [2,4,6,8,10,12,14,16]
B = 1×8
2 4 6 8 10 12 14 16
How can I combine these two to give me a third matrix C, which is as follows?
C = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
C = 1×16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
So, basically, C should be [A(:,1), B(:,1), A(:,2), B(:,2), ...]

채택된 답변

Stephen23
Stephen23 2023년 3월 17일
A = [1,3,5,7;9,11,13,15;17,19,21,23]
A = 3×4
1 3 5 7 9 11 13 15 17 19 21 23
B = [2,4,6,8;10,12,14,16;18,20,22,24]
B = 3×4
2 4 6 8 10 12 14 16 18 20 22 24
C = reshape(permute(cat(3,A,B),[1,3,2]),size(A,1),[])
C = 3×8
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
  댓글 수: 1
Stephen23
Stephen23 2023년 3월 17일
A = [1,3,5,7;9,11,13,15;17,19,21,23];
B = [2,4,6,8;10,12,14,16;18,20,22,24];
Another approach:
C = repelem(A,1,2);
C(:,2:2:end) = B
C = 3×8
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

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

추가 답변 (1개)

Sarvesh Kale
Sarvesh Kale 2023년 3월 14일
Hi Jake,
You can see the following code snippet
A = [1,3,5,7,9,11,13,15];
B = [2,4,6,8,10,12,14,16];
C=[A;B] % row wise concatenation
C = 2×8
1 3 5 7 9 11 13 15 2 4 6 8 10 12 14 16
C=C(:)'; % traversal will be column wise as matrix elements are stored in column major format
C
C = 1×16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
I hope this helps your query
Thank you
  댓글 수: 1
Jake
Jake 2023년 3월 17일
Thank you for the solution, @Sarvesh Kale! I'm curious to know how could one do this when the matrices are multi-dimensional. For instance, what if,
A = [1,3,5,7;9,11,13,15;17,19,21,23]
A = 3×4
1 3 5 7 9 11 13 15 17 19 21 23
B = [2,4,6,8;10,12,14,16;18,20,22,24]
B = 3×4
2 4 6 8 10 12 14 16 18 20 22 24
How could we get the matrix C by combining every-other column of A, and B, such that, (simply to demonstrate)?
C = [1,2,3,4,5,6,7,8; 9,10,11,12,13,14,15,16; 17,18,19,20,21,22,23,24]
C = 3×8
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by