Reputation: 209
I'm trying to write a program to check the results of all possible combinations of 5 separate 5x5 matrices, where each element in all the matrices are booleans. However, my problem is I can't figure out a way to cause the matrices to check through every combination.
Illustrating what I would like to happen for a 2x2 matrix. I want my program to produce the matrix as follow:
(1) [0 0;0 0]
(2) [1 0;0 0]
(3) [1 1;0 0]
(4) [1 1;1 0]
(5) [1 1;1 1]
(6) [1 0;0 1]
(7) [1 1;0 1]
…
and so on until every possible matrix has been done. How I may achieve this, so that I do some operation with every one of these matrix combinations?
(I realise this will probably take an impossibly long time to completely cycle through 5 5x5 matrices, however I also wish to do it for smaller matrices (3 3x3's) and I would also like to just leave it running as long as possible to check through as many possible 5 5x5's and seeing, out of the ones I've checked, which is the best result.)
Upvotes: 0
Views: 204
Reputation: 2557
So, as you can see, you have several combinations of a zero matrix you want to add a one, right?
We could say that you have the following possible combinations you want to add a one. For the 2 dimensional case:
addOnes =
Empty matrix: 1-by-0
onePossibleCombination =
0 0
0 0
addOnes =
1
onePossibleCombination =
1 0
0 0
addOnes =
2
onePossibleCombination =
0 0
1 0
addOnes =
3
onePossibleCombination =
0 1
0 0
addOnes =
4
onePossibleCombination =
0 0
0 1
addOnes =
1 2
onePossibleCombination =
1 0
1 0
addOnes =
1 3
onePossibleCombination =
1 1
0 0
addOnes =
1 4
onePossibleCombination =
1 0
0 1
addOnes =
2 3
onePossibleCombination =
0 1
1 0
addOnes =
2 4
onePossibleCombination =
0 0
1 1
addOnes =
3 4
onePossibleCombination =
0 1
0 1
addOnes =
1 2 3
onePossibleCombination =
1 1
1 0
addOnes =
1 2 4
onePossibleCombination =
1 0
1 1
addOnes =
1 3 4
onePossibleCombination =
1 1
0 1
addOnes =
2 3 4
onePossibleCombination =
0 1
1 1
addOnes =
1 2 3 4
onePossibleCombination =
1 1
1 1
How can we achieve that? All we need is to take all combinations taken by 0, 1, 2, 3 and 4. For that we use the nchoosek
method as follows:
matrixSize = 2;
for k=0:matrixSize^2
combinations=nchoosek(1:matrixSize^2,k);
for m = 1:size(combinations,1)
addOnes = combinations(m,:);
onePossibleCombination = zeros(matrixSize,matrixSize);
onePossibleCombination(addOnes) = 1;
% Do your operation here with the matrix onePossibleCombination
end
end
Upvotes: 2