Generation of all possible vectors with constraints

3 views (last 30 days)
Hi
I want to create all possible vectors comprised of 0, 1 or/and -1 such that length of each vector is 7 and it contains exactly 3 zeros. Finally the result should be in a matrix form in which each row is an aforsaid type vector.
e.g. M= 1 0 1 -1 0 -1 0
0 0 -1 0 1 1 1
-1 -1 -1 0 -1 0 0
:::::::::::::::::::::::
Thank you!

Accepted Answer

Naren
Naren on 7 May 2024
Hello,
To generate all possible vectors of length 7 that contains exactly 3 zeros and each of the remaining elements being either 1 or -1, and then to represent these vectors in a matrix form with each row being one of these vectors in MATLAB, you can use the following code:
n = 7;
zp = combnk(1:n, 3); % Positions for zeros
s = size(zp, 1) * 2^(n-3); % Total number of vectors with 3 zeros and the rest being either 1 or -1
M = zeros(s, n);
c = 1;
for i = 1:size(zp, 1)
non_zero_combinations = dec2bin(0:15) - '0';
non_zero_combinations(non_zero_combinations == 0) = -1;
% Insert zeros and non-zeros into the vectors
for j = 1:size(non_zero_combinations, 1)
v = ones(1, n);
% Set the three chosen positions to zero
v(zp(i, :)) = 0;
% Fill the remaining positions with current combination of 1s and -1s
non_zp = setdiff(1:n, zp(i, :));
for k = 1:length(non_zp)
v(non_zp(k)) = non_zero_combinations(j, k);
end
% Add the v to the matrix
M(c, :) = v;
c = c + 1;
end
end
Regards.
  4 Comments
Dyuman Joshi
Dyuman Joshi on 9 May 2024
Edited: Dyuman Joshi on 9 May 2024
@Sheet, The 0:15 i.e. 16 values comes from 2^4 non-zeros combinations (2 values for 7-3 = 4 spaces) for a particular set of placementof elements in 7 spaces.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!