Consider two matrices:
a = [1 2 3; 4 5 6; 7 8 10]
a =
1 2 3
4 5 6
7 8 10
and b=a + 10
b =
11 12 13
14 15 16
17 18 20
first, I am trying to obtain all possible combination of rows (1st row of 'a' and all rows of 'b', second row of 'a' and all rows of 'b' and so on) such that the output is
c =
1 2 3 11 12 13
4 5 6 11 12 13
7 8 10 11 12 13
1 2 3 14 15 16
4 5 6 14 15 16
7 8 10 14 15 16
1 2 3 17 18 20
4 5 6 17 18 20
7 8 10 17 18 20
secondly for each row, I am storing the first 3 and the last 3 columns in a single index of a 3 index vector. So in this example the vector of combosets is 2x3x9 where element is
combosets(:,:,1) =
1 2 3
11 12 13
combosets(:,:,2) =
4 5 6
11 12 13
and so on. The code I am using is below. Is there any better and faster way to do this and prefarably step 1 and 2 combined?
Thanks in advance!
clcclearvars;a = [1 2 3; 4 5 6; 7 8 10]; % 3 by 3 matrix
b=a + 10; % 3 by 3 matrix
r=size(a,1);combosets=zeros(r-1,r,r*r);d={NaN};% Step 1: storing different combination of rows in cell
for k=1:1:r c=vertcat(horzcat(a(:,:),repmat(b(k,:),r,1)),horzcat(a(:,:),repmat(b(k,:),r,1)),horzcat(a(:,:),repmat(b(k,:),r,1))); d{k}=(unique(c,'rows'));endddash=cell2mat(d'); % making it a matrix again
% Step 2: storing in a multidimensional array
for j=1:1:r*r rowset1=ddash(j,1:3); rowset2=ddash(j,4:6); combosets(:,:,j)=[rowset1;rowset2]; end
Best Answer