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 vues (au cours des 30 derniers jours)
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);
  2 commentaires
Jan
Jan le 29 Jan 2023
Modifié(e) : Jan le 29 Jan 2023
What you call "variable" is called "element" in Matlab.
"(i.e. 5-10 variables)" - these are 6 elements, not 5.

Connectez-vous pour commenter.

Réponse acceptée

Jan
Jan le 29 Jan 2023
Modifié(e) : Jan le 29 Jan 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

Plus de réponses (0)

Catégories

En savoir plus sur Problem-Based Optimization Setup dans Help Center et File Exchange

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by