changing position of numbers in a vector
조회 수: 9 (최근 30일)
이전 댓글 표시
Im new in matlab, i hope someone can help me with my problem. I need to make a code to solve this Cobinatoric example. I have a vector with 6 numbers where 2 of them are 1 and the rest are 0 as you can see below
A=[1 1 0 0 0 0]
I want to make a code which can help me change the position of all (1)s and put them in all the possible positions as you can see bellow without changing it all of them by myself, because my code is not only 5 numbers, i have a huge number.
A=[0 1 1 0 0 0]
A=[0 0 1 1 0 0]
A=[0 0 0 1 1 0]
A=[0 0 0 0 1 1]
A=[1 0 1 0 0 0]
A=[1 0 0 1 0 0]
A=[1 0 0 0 1 0]
A=[1 0 0 0 0 1]
A=[0 1 0 1 0 0]
A=[0 1 0 0 1 0]
A=[0 1 0 0 0 1]
A=[0 0 1 0 1 0]
A=[0 0 1 0 0 1]
A=[0 0 0 1 0 1]
댓글 수: 0
답변 (4개)
Andrei Bobrov
2013년 5월 20일
편집: Andrei Bobrov
2013년 5월 20일
out = unique(perms([1 1 0 0 0 0]),'rows');
or [EDIT]
A = [1 1 1 1 0 0 0 0 0 0];
n = numel(A);
b = nnz(A);
M = 0:ones(1,n)*pow2(n-1:-1:0)';
z = rem(floor(M(:)*pow2(1-n:0)),2);
out = z(sum(z,2) == b,:);
댓글 수: 3
Triveni
2015년 10월 31일
@Andrei Bobrov
If A= [-45 -45 -45 -45 -45 -45 0 0 0 0 0 0 0 0 45 45 45 45 45 45]
then how can be write??
David Sanchez
2013년 5월 20일
Andrei's answer maybe the best choice, but in case you want to see what's behind:
A=zeros(1,6);
for k=1:size(A,2)
A=zeros(1,6);
A(k) = 1;
for n = k+1:size(A,2)
if n>k+1
A(n-1) = 0;
end
A(n) = 1
end
end
Roger Stafford
2013년 5월 20일
This problem is naturally made for Matlab's 'nchoosek' function. This method requires no rejection afterward and will therefore be easiest on your memory. Let A be a row vector of ones and zeros.
n = size(A,2);
k = sum(A==1);
C = nchoosek(1:n,k);
m = size(C,1); % m will equal n!/k!/(n-k)!
B = zeros(m,n);
B(repmat((1-m:0)',1,k)+m*C) = 1; % Place ones according to indices in C
The desired position combinations will appear in the rows of B, with k ones in each row.
Note: Beware of "huge" numbers! If you have, say, 15 ones and 15 zeros in A, the number of possible arrangements of them is an enormous 155,117,520.
댓글 수: 0
Mian Jehanzaib
2016년 12월 22일
How about creating one possible combination row at a time in a for loop and not creating a huge matrix at once?
I don't require to store the all possibilities in a matrix rather I need to generate them one at a time. Could you suggest any solution please
댓글 수: 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!