Find different possible combinations of the rows of two matrices.
조회 수: 8 (최근 30일)
이전 댓글 표시
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
채택된 답변
Johannes Fischer
2020년 9월 8일
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개)
Adam Danz
2020년 9월 8일
편집: Adam Danz
2020년 9월 8일
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
Adam Danz
2020년 9월 8일
"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 🙂.
참고 항목
카테고리
Help Center 및 File Exchange에서 Particle & Nuclear Physics에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!