フィルターのクリア

detecting elements change in an array

2 ビュー (過去 30 日間)
Tariq Hammoudeh
Tariq Hammoudeh 2022 年 1 月 8 日
編集済み: Tariq Hammoudeh 2022 年 1 月 8 日
I have an array of zeros:
x=zeros(1,36);
and in my program i change some elements of it to 1 using for example
x(6)=1;
Now i will turn some of those 1s to 2s, but is there a way i can say:
while all 1s didnt turn to 2s
.........
So basically i wanna keep inputting something as long as all the 1s didnt become 2s and it breaks out once all 1s became 2s

採用された回答

Walter Roberson
Walter Roberson 2022 年 1 月 8 日
while any(x==1)
  1 件のコメント
Tariq Hammoudeh
Tariq Hammoudeh 2022 年 1 月 8 日
編集済み: Tariq Hammoudeh 2022 年 1 月 8 日
Thank you,

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

その他の回答 (1 件)

Image Analyst
Image Analyst 2022 年 1 月 8 日
Try this:
x=zeros(1,36);
% Get 20 random indexes to turn to 1's.
indexes = sort(randperm(length(x), 20));
% Initialize by turning some of the zeros into ones.
x(indexes) = 1;
% Set up a failsafe
maxIterations = 10000; % Way more than you think it would ever need.
loopCounter = 1;
% Now loop over the 1's, turning some of them to 2's
% until all the 1's have been turned into 2.
while any(x == 1) && loopCounter < maxIterations
fprintf('Iteration #%d.\n', loopCounter)
% Get indexes that are 1.
indexes = find(x == 1)
% Pick a random one of those to turn to a 2
% or whatever method you want to use....
randomIndex = randi(length(indexes))
x(indexes(randomIndex)) = 2
loopCounter = loopCounter + 1;
end
x
fprintf('All done after %d iterations.\n', loopCounter)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by