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 visualizaciones (últimos 30 días)
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);

Respuesta aceptada

Jan
Jan el 29 de En. de 2023
Editada: Jan el 29 de En. de 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

Más respuestas (0)

Categorías

Más información sobre Problem-Based Optimization Setup en Help Center y File Exchange.

Productos


Versión

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by