How to I combine different numbers of columns from two matrices?
조회 수: 2 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
채택된 답변
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
추가 답변 (1개)
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!