Generation of all possible vectors with constraints

조회 수: 1 (최근 30일)
Sheet
Sheet 2024년 5월 7일
댓글: Sheet 2024년 5월 10일
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
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
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.
Sheet
Sheet 2024년 5월 10일
Thank you Dyuman! I got it।

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Elementary Math에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by