# Generate specific binary combination

3 vues (au cours des 30 derniers jours)
Khoa Tran le 30 Nov 2023
Commenté : Khoa Tran le 30 Nov 2023
Hi guys,
I am working with binary combinations and encountering a problem with memory as the N value gets bigger. I am using this function to create my binary combinations array:
N = 4;
dec2bin(0:2^N-1) - '0'
I need to iterate each combination in the array in my calculation (i.e., iterating each row of the array at a time). Is there a way that we can generate a specific combination without having to create the whole array beforehand and use only one row at a time?
For example, 7th row in the array is [0 1 1 0]. I want to create [0 1 1 0], do the calculation, then continue to 8th row and so on.
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Réponse acceptée

Walter Roberson le 30 Nov 2023
N = 4;
for K = 0 : 2^N - 1
thiscombo = dec2bin(K,N);
stuff
end
##### 1 commentaireAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens
Khoa Tran le 30 Nov 2023
Thanks @Walter Roberson. This is just what I need.

Connectez-vous pour commenter.

### Plus de réponses (1)

Chunru le 30 Nov 2023
You can put the dec2bin inside the loop so it won't be a big array.
N = 4;
for i=0:2^N-1
c = dec2bin(i, N) - '0'
end
c = 1×4
0 0 0 0
c = 1×4
0 0 0 1
c = 1×4
0 0 1 0
c = 1×4
0 0 1 1
c = 1×4
0 1 0 0
c = 1×4
0 1 0 1
c = 1×4
0 1 1 0
c = 1×4
0 1 1 1
c = 1×4
1 0 0 0
c = 1×4
1 0 0 1
c = 1×4
1 0 1 0
c = 1×4
1 0 1 1
c = 1×4
1 1 0 0
c = 1×4
1 1 0 1
c = 1×4
1 1 1 0
c = 1×4
1 1 1 1
##### 1 commentaireAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens
Khoa Tran le 30 Nov 2023
Thanks @Chunru. A simple and effective solution.

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

R2023b

### Community Treasure Hunt

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

Start Hunting!

Translated by