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 次查看(过去 30 天)
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);

采纳的回答

Jan
Jan 2023-1-29
编辑:Jan 2023-1-29
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Problem-Based Optimization Setup 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by