Generation of all possible vectors with constraints
3 ビュー (過去 30 日間)
古いコメントを表示
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!
採用された回答
Naren
2024 年 5 月 7 日
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 件のコメント
Dyuman Joshi
2024 年 5 月 9 日
編集済み: Dyuman Joshi
2024 年 5 月 9 日
@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.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!