Can I run all cases of switch ? if not, is there another way ?

4 ビュー (過去 30 日間)
omar th
omar th 2023 年 2 月 21 日
コメント済み: omar th 2023 年 2 月 25 日
The attached code is running only one of the cases randomly. My question Can I execute all cases in random way, for example run the third loop (case 3) then the first loop (case 1) and after that the second loop (case 2 ) and then iterate the MAIN LOOP as shown below. If that can't be done, I appreciate another way if its possible.
Thanks in advance
for q=1:5 % MAIN LOOP
t = randperm(3,1);
switch t
case 1
for q1=1:10 % Loop 1
disp(1);
end
case 2
for q2=1:10 % Loop 2
disp(2);
end
case 3
for q3=1:10 % Loop 3
disp(3);
end
end
end

採用された回答

dpb
dpb 2023 年 2 月 21 日
編集済み: dpb 2023 年 2 月 21 日
That's just putting the switch block inside another loop...
...
M=5; % outer loop counter
N=3; % number switch blocks
for q=1:M % MAIN LOOP
for t=randperm(N) % execute the |switch| randomly in sequence for all cases
switch t
case 1
for q1=1:10 % Loop 1
disp(1);
end
case 2
for q2=1:10 % Loop 2
disp(2);
end
case 3
for q3=1:10 % Loop 3
disp(3);
end
end
end
end
The above will do all cases in random order each time with no repeats; one could choose alternate sampling patterns as well, of course of "N of K" or even not require no replications.
  6 件のコメント
dpb
dpb 2023 年 2 月 21 日
See patched Answer/Comment above...
N=3;
for i=1:2
fprintf('i: %d\n',i)
for t=randperm(N)
disp(t)
end
end
i: 1
2 1 3
i: 2
2 3 1
omar th
omar th 2023 年 2 月 21 日
Sorry for any an inconvienence, Its worked I really appreciate that

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

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2023 年 2 月 21 日
編集済み: Walter Roberson 2023 年 2 月 22 日
I already gave you code that permits you to exactly control the minimum number of times each of the cases is to be executed (in a random order), with any remaining iterations to be chosen at random.
  2 件のコメント
dpb
dpb 2023 年 2 月 21 日
Hadn't realized you'd already solved it, Walter. This was first I saw OP's plea...
omar th
omar th 2023 年 2 月 25 日
@Walter Roberson thank you so much, and sorry for not realizing your answer.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by