MATLAB: Generate a kind of arrays related to bit

arraycode generation

Hi
I would like to generate
N = 4
a{1} = 1111111100000000 a{2} = 1111000011110000 a{3} = 1100110011001100 a{4} = 1010101010101010
N = 5
a{1} = 11111111111111110000000000000000 a{2} = 11111111000000001111111100000000 a{3} = 11110000111100001111000011110000 a{4} = 11001100110011001100110011001100 a{5} = 10101010101010101010101010101010
this kind of arrays. And I would like to get sum(b(a{i}==1)) for all i as well.
In fact, the goal is only to get the array a{idx} where [~,idx] = min(cp) with cp = sum(b(a{i}==1))
Anyone has a faster solution rather than double for-loop?
Thanks,

Best Answer

I guess the algorithm to create the cell "a":
a{1} = [1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0];
a{2} = [1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0];
a{3} = [1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0];
a{4} = [1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0];
If we now concatenate the rows, we get the binary representation of the values 2^N-1 to 0 as columns:
A = cat(1, a{:})
>> A = [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0; ...
1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0; ...
1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0; ...
1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0];
Instead of creating the rows of the cell "a" it is easier to create the matrix directly:
N = 4;
A = (dec2bin(2^N-1:-1:0) - '0').';
If I guess that "b" is a numerical vector of the same size:
b = rand(1, 16);
cp = A * b(:);
[~, idx] = min(cp);
result = A(idx, :);