필터 지우기
필터 지우기

generate the binary sequence

조회 수: 8 (최근 30일)
Bear
Bear 2014년 11월 27일
댓글: Bear 2014년 11월 28일
I have a code to generate the binary sequence that only contains m zeros and n ones. For example, m=n=2. then the number of combinations of the binary sequence is 6,nchoosek(4,2). My code was fine to output the 6 combinations, but mostly 2 combinations are the same. My question is how to avoid a combination of sequence show twice?
The code is following:
% clear all;
m = input('How many zeroes do you need \n');
n = input('how many ones do you need\n');
lnk=nchoosek(m+n,n);
i=n+m;
for kk=1:lnk
% m = input('How many zeroes do you need \n');
% n = input('how many ones do you need\n');
if i<=1
disp('size of binary sequence is out of range');
else
%Binary sequence contains m zeros and n ones in any order
x1=zeros(1,i);
x1(randperm(i,n))=1
%count down the number of switches in such a Binary sequence x1;
switches=0;
for k=1:length(x1)-1
if x1(k)==0 && x1(k+1)==1
switches= switches+1;
elseif x1(k)==1 && x1(k+1)==0
switches=switches+1;
end
end
Av(kk)=switches;
end
end
Also, my result shows like:
How many zeroes do you need
2
how many ones do you need
2
x1 =
0 0 1 1
x1 =
0 0 1 1
x1 =
0 1 1 0
x1 =
1 0 1 0
x1 =
1 1 0 0
x1 =
1 1 0 0
Av =
1 1 2 3 1 1
tot_combination =
6
  댓글 수: 1
Bear
Bear 2014년 11월 28일
again, my output is wrong, because it's missing one or two combinations. Therefore I want to correct this code and output the unique 6 combinations. I hope someone could help me to correct this code.

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

채택된 답변

Guillaume
Guillaume 2014년 11월 27일
편집: Guillaume 2014년 11월 28일
Maybe I'm misunderstanding something but to me it looks like your code is wrong, it's missing for ex. 0 1 0 1 as an output.
The simplest way to obtain all unique permutations of a sequence is:
m = 2; n = 2;
seqs = unique(perms([zeros(1, m) ones(1, n)]), 'rows')
There are indeed 6 combinations, but not the ones you return in your example.
  댓글 수: 5
Guillaume
Guillaume 2014년 11월 28일
편집: Guillaume 2014년 11월 28일
There's nothing stopping you from iterating over the rows or transforming the rows into a cell array, or whatever data structure you wish.
Or you could just use diff to detect the transitions between columns (transition will show up as either -1 or 1) and sum these up:
m = 2; n = 2; %for example
seqs = unique(perms([zeros(1, m) ones(1, n)]), 'rows')
transitions = sum(abs(diff(seqs, [], 2)), 2)
Bear
Bear 2014년 11월 28일
I see what you mean now, thanks for your great help again.

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by