Generation of all possible vectors with constraints

3 vues (au cours des 30 derniers jours)
Sheet
Sheet le 7 Mai 2024
Commenté : Sheet le 10 Mai 2024
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!

Réponse acceptée

Naren
Naren le 7 Mai 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 commentaires
Dyuman Joshi
Dyuman Joshi le 9 Mai 2024
Modifié(e) : Dyuman Joshi le 9 Mai 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.
Sheet
Sheet le 10 Mai 2024
Thank you Dyuman! I got it।

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by