I have a string with 10 variables created using randi, between 0 and 1, in the last 5 variables (i.e 5-10 variables) i want maximum 2 places with 1 only (eg:- 1011101001).

2 visualizzazioni (ultimi 30 giorni)
I want in the last 5 variables, there to be maximum of two 1's only
Acceptable :- 1110110100, 1011100010, 0010101100 etc.
Not Acceptable :- 1101011001 etc.
nVar = 10;
a = randi([0, 1], 1, nVar);

Risposta accettata

Jan
Jan il 29 Gen 2023
Modificato: Jan il 29 Gen 2023
nVar = 10;
last = 5;
a = randi([0, 1], 1, nVar - last);
b = zeros(1, last);
n = randi([0, 2]); % 0, 1 or 2
b(randperm(last, n)) = 1; % Elements at n indices of 5 set o 1
result = [a, b]
result = 1×10
1 0 1 0 1 0 0 1 1 0

Più risposte (0)

Categorie

Scopri di più su Problem-Based Optimization Setup in Help Center e File Exchange

Prodotti


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by