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);
  2 件のコメント
Jan
Jan 2023 年 1 月 29 日
編集済み: Jan 2023 年 1 月 29 日
What you call "variable" is called "element" in Matlab.
"(i.e. 5-10 variables)" - these are 6 elements, not 5.

サインインしてコメントする。

採用された回答

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 Center および File ExchangeProblem-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