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

2 Ansichten (letzte 30 Tage)
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.

Akzeptierte Antwort

Mohammad Abouali
Mohammad Abouali am 23 Okt. 2015
Bearbeitet: Mohammad Abouali am 23 Okt. 2015
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

Weitere Antworten (1)

Guillaume
Guillaume am 26 Okt. 2015
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.

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by