How to I combine different numbers of columns from two matrices?

2 ビュー (過去 30 日間)
PBB
PBB 2015 年 10 月 23 日
コメント済み: Mohammad Abouali 2015 年 10 月 26 日
I have two matrices, A and B, and would like to generate a third matrix, C, that contains column 1 of A followed by columns 1:3 of B, then column 2 of A followed by columns 4:6 of B, and so on, until the end of matrix A is reached. I know I can individually generate each group of [A(:,x),B(:,x:x+2)] and then concatenate them, but I'd like to make one loop function to read matrices of any size.

採用された回答

Mohammad Abouali
Mohammad Abouali 2015 年 10 月 23 日
編集済み: Mohammad Abouali 2015 年 10 月 23 日
No loop is needed. Check this:
% Sample A and B
A=repmat(1:4,3,1); % A has its column filled with number 1 to 4
A =
1 2 3 4
1 2 3 4
1 2 3 4
B=repmat(5:16,3,1); % B has its column filled with number 5 to 16
B =
5 6 7 8 9 10 11 12 13 14 15 16
5 6 7 8 9 10 11 12 13 14 15 16
5 6 7 8 9 10 11 12 13 14 15 16
nColA=size(A,2);
if (size(B,2)<(nColA*3))
error('B does not have enough column');
end
if (size(B,1)~=size(A,1))
error('A and B must have same number of rows');
end
% Initializing C
C=NaN(size(A,1),nColA*4);
% PLacing A in C
C(:,((1:nColA)-1)*4+1)=A;
% Placeing B in C
C(:,(1:nColA*3)+floor(((1:nColA*3)-1)/3)+1)=B;
C =
1 5 6 7 2 8 9 10 3 11 12 13 4 14 15 16
1 5 6 7 2 8 9 10 3 11 12 13 4 14 15 16
1 5 6 7 2 8 9 10 3 11 12 13 4 14 15 16
  2 件のコメント
PBB
PBB 2015 年 10 月 26 日
Worked perfectly. Thanks!
Mohammad Abouali
Mohammad Abouali 2015 年 10 月 26 日
You are welcome

サインインしてコメントする。

その他の回答 (1 件)

Guillaume
Guillaume 2015 年 10 月 26 日
I would have done it with a logical array:
A=repmat(1:4,3,1); % A has its column filled with number 1 to 4
B=repmat(5:16,3,1); % B has its column filled with number 5 to 16
filler = repmat(logical([1 0 0 0]), size(A)); %logical array. 1 indicates use A, 0 indicates use B.
C = zeros(size(filler)); %output array
C(filler) = A; %fill 1 with A
C(~filler) = B %fill 0 with B
Simpler than calculating column indices.

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by