Reputation: 3075
B is a [1x8] matrix which can also be considered as two halves as follows:
B = -1 -1 0 0 0 0 1 1
Here there can be either one, two, three or four -1
's in the first half, and there should be equal number of 1
's in the second half. It should be done in linear combinations.
For example, if there are two -1
's in the first half, they can be placed in 4 choose 2 = 6
ways, and for each of them there will be 6 ways to place the two 1
's in the second half. So the system has a total of 6*6 = 36 ways. i.e. 36 different values for B's if there are two -1
's in the first half.
How can I do this?
Upvotes: 5
Views: 2151
Reputation: 124563
Here is another solution:
%# generate all possible version of first half
h1 = num2cell(-(dec2bin(1:15)-'0'),2);
%# generate all possible version of second half
h2 = arrayfun(@(i) unique(perms([zeros(1,4-i) ones(1,i)]),'rows'), (1:4)', 'UniformOutput',false);
%'# number of 1s in each row of h1
n = -cellfun(@sum, h1);
%# get final result by combining h1 and h2
B = cellfun(@(a,b) [repmat(a,size(b,1),1) b], h1, h2(n), 'UniformOutput',false);
B = cell2mat(B);
The result:
B =
0 0 0 -1 0 0 0 1
0 0 0 -1 0 0 1 0
0 0 0 -1 0 1 0 0
0 0 0 -1 1 0 0 0
0 0 -1 0 0 0 0 1
0 0 -1 0 0 0 1 0
0 0 -1 0 0 1 0 0
0 0 -1 0 1 0 0 0
0 0 -1 -1 0 0 1 1
0 0 -1 -1 0 1 0 1
0 0 -1 -1 0 1 1 0
0 0 -1 -1 1 0 0 1
0 0 -1 -1 1 0 1 0
0 0 -1 -1 1 1 0 0
0 -1 0 0 0 0 0 1
0 -1 0 0 0 0 1 0
0 -1 0 0 0 1 0 0
0 -1 0 0 1 0 0 0
0 -1 0 -1 0 0 1 1
0 -1 0 -1 0 1 0 1
0 -1 0 -1 0 1 1 0
0 -1 0 -1 1 0 0 1
0 -1 0 -1 1 0 1 0
0 -1 0 -1 1 1 0 0
0 -1 -1 0 0 0 1 1
0 -1 -1 0 0 1 0 1
0 -1 -1 0 0 1 1 0
0 -1 -1 0 1 0 0 1
0 -1 -1 0 1 0 1 0
0 -1 -1 0 1 1 0 0
0 -1 -1 -1 0 1 1 1
0 -1 -1 -1 1 0 1 1
0 -1 -1 -1 1 1 0 1
0 -1 -1 -1 1 1 1 0
-1 0 0 0 0 0 0 1
-1 0 0 0 0 0 1 0
-1 0 0 0 0 1 0 0
-1 0 0 0 1 0 0 0
-1 0 0 -1 0 0 1 1
-1 0 0 -1 0 1 0 1
-1 0 0 -1 0 1 1 0
-1 0 0 -1 1 0 0 1
-1 0 0 -1 1 0 1 0
-1 0 0 -1 1 1 0 0
-1 0 -1 0 0 0 1 1
-1 0 -1 0 0 1 0 1
-1 0 -1 0 0 1 1 0
-1 0 -1 0 1 0 0 1
-1 0 -1 0 1 0 1 0
-1 0 -1 0 1 1 0 0
-1 0 -1 -1 0 1 1 1
-1 0 -1 -1 1 0 1 1
-1 0 -1 -1 1 1 0 1
-1 0 -1 -1 1 1 1 0
-1 -1 0 0 0 0 1 1
-1 -1 0 0 0 1 0 1
-1 -1 0 0 0 1 1 0
-1 -1 0 0 1 0 0 1
-1 -1 0 0 1 0 1 0
-1 -1 0 0 1 1 0 0
-1 -1 0 -1 0 1 1 1
-1 -1 0 -1 1 0 1 1
-1 -1 0 -1 1 1 0 1
-1 -1 0 -1 1 1 1 0
-1 -1 -1 0 0 1 1 1
-1 -1 -1 0 1 0 1 1
-1 -1 -1 0 1 1 0 1
-1 -1 -1 0 1 1 1 0
-1 -1 -1 -1 1 1 1 1
Upvotes: 2
Reputation: 74940
You can first generate all possible permutations of ones and zeros, and then throw away the superfluous ones.
%# make permutations using dec2bin (start from 17 since it's the first solution)
allB = str2double(num2cell(dec2bin(17:255)));
%# change sign in the first half, then check that the total is ok
allB(:,1:4) = - allB(:,1:4);
allB = allB(sum(allB,2)==0,:);
Each row of allB
is a possible value for B
Upvotes: 5