Find different possible combinations of the rows of two matrices.
15 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Tuhin Choudhury
el 8 de Sept. de 2020
Comentada: Adam Danz
el 8 de Sept. de 2020
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!
clc
clearvars;
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'));
end
ddash=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
0 comentarios
Respuesta aceptada
Johannes Fischer
el 8 de Sept. de 2020
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);
% create repetitions of values
a = repmat(a, [r, 1]);
b = repelem(b, r, 1);
% create combination matrix
c = [a b];
% reshape into combosets
combosets = reshape(c', 3, 2, 9);
% permute to get dimensions right
combosets = permute(combosets, [2, 1, 3]);
1 comentario
Más respuestas (1)
Adam Danz
el 8 de Sept. de 2020
Editada: Adam Danz
el 8 de Sept. de 2020
Fast & clean 2-liner:
a = [1 2 3; 4 5 6; 7 8 10];
b = a + 10;
c = [repmat(a,size(b,1),1), repelem(b, size(a,1),1)];
combosets = permute(reshape(c.',3,2,9),[2,1,3]);
5 comentarios
Adam Danz
el 8 de Sept. de 2020
"I wish I could accept more than 1 answer"
You accepted the right one if it works for your data and it make sense to you. The time difference is so small that readability and understandability are important factors. Plus, I like when newer contributors get recognition for their contributions and encouragement to continue doing so 🙂.
Ver también
Categorías
Más información sobre Particle & Nuclear Physics en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!