create a binary sequence that consisting of m zeros and n ones in any order.

I need help to program a matlab code to generate a binary sequence that contains m zeros and n ones. I created a N lengths of zero, x1=zeros(1,N), but how to add n ones into the sequence of zeros.

 Respuesta aceptada

The easiest way:
x1 = [zeros(1,N) ones(1,M)];

1 comentario

Thx alot and it works well, but I forgot to say the zeros and ones have to be placed in random order. Do you have any ideas how to do this.

Iniciar sesión para comentar.

Más respuestas (3)

Or perhaps you want them in random order:
x = zeros(1,m+n);
p = randperm(1:m+n,n);
x(p) = ones(1,n);

4 comentarios

Yes, I want them in random order, but there is something wrong with your 2nd line above there.
You may have an old version where randperm() did not allow a second input argument. Please upgrade.
There is an error in
p = randperm(1:m+n,n);
Yes, it should have been
p = randperm(m+n,n);

Iniciar sesión para comentar.

Azzi Abdelmalek
Azzi Abdelmalek el 23 de Nov. de 2014
Editada: Azzi Abdelmalek el 23 de Nov. de 2014
x1=[zeros(1,5) ones(1,4)]
%or
N=5;
n=4;
X1=1:n+N>N

4 comentarios

Thank you and it works well, but I forgot to say the zeros and ones have to be placed in random order. Do you have any ideas how to do this.
N=5;
M=4;
X1=zeros(1,N+M);
X1(randperm(N+M,M))=1
Thank you. That was what I asked for.
There is a question on my further programming this code, 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. However, the combinations are not unique. one or two combinations show twice. Here is the detail of question, you may want to click and take a look. generate the binary sequence Again, thank you for the great helps.

Iniciar sesión para comentar.

Categorías

Más información sobre MATLAB en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 23 de Nov. de 2014

Comentada:

el 27 de Nov. de 2014

Community Treasure Hunt

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

Start Hunting!

Translated by