Need help - How to generate predefined subsets?
1 view (last 30 days)
Show older comments
All:
I have a 5 X 4 matrix defined as
v = [
1 2 3 4;
5 6 7 8 ;
9 10 11 12;
13 14 15 16;
17 18 19 20];
I need to write a code to generate all possible unique combinations of a group of 4 elements. The group needs to contain 1 element from each column. For example:
C1 = 1 2 3 4
C2 = 1 6 7 8
C3 = 1 14 19 20
...
Any help will be greatly appreciated.
0 Comments
Answers (2)
the cyclist
on 12 Jul 2012
Edited: the cyclist
on 12 Jul 2012
Here's one way. There might be better ones.
Download this code from the File Exchange:
Then run this code:
v = [1 2 3 4;
5 6 7 8 ;
9 10 11 12;
13 14 15 16;
17 18 19 20];
arrayOfIndices = combinator(5,4);
C = [v(arrayOfIndices(:,1),1), ...
v(arrayOfIndices(:,2),2), ...
v(arrayOfIndices(:,3),3), ...
v(arrayOfIndices(:,4),4)];
This will put all the combinations into one 625 X 4 array, C.
0 Comments
Teja Muppirala
on 12 Jul 2012
Another idea:
[C1,C2,C3,C4] = ndgrid(1:5);
allCombinations = [v(C1,1) v(C2,2) v(C3,3) v(C4,4)]
Or a more flexible way, which will work for any sized v:
[nRows, nCols] = size(v);
C = cell(1,nCols);
[C{:}] = ndgrid(1:nRows);
C = cell2mat(cellfun(@(x)x(:),C,'uniform',0));
C = bsxfun(@plus, C,nRows*(0:nCols-1) );
allCombinations = v(C)
0 Comments
See Also
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!