# Generation of all possible vectors with constraints

6 Ansichten (letzte 30 Tage)
Sheet am 7 Mai 2024
Kommentiert: Sheet am 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!
##### 1 Kommentar-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden
Sheet am 7 Mai 2024
Yes.

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

Naren am 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 Kommentare2 ältere Kommentare anzeigen2 ältere Kommentare ausblenden
Dyuman Joshi am 9 Mai 2024
Bearbeitet: Dyuman Joshi am 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 am 10 Mai 2024
Thank you Dyuman! I got it।

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Logical finden Sie in Help Center und File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by