# How can I randomly excuted for loops inside MAIN FOR LOOP instead of run them in ordered ?

5 visualizaciones (últimos 30 días)
omar th el 31 de En. de 2023
Respondida: Steven Lord el 25 de Feb. de 2023
I want to select one of these for loops randmly to excute them NOT in ordered from loop 1 to loop 2 to Loop 3. for example in the first iteration of the main loop, Loop 3 is executed first and in the second iteration again selecting is randomly.
for q=1:100 % MAIN LOOP
for q1=1:10 % Loop 1
do some calculation
end
for q2=1:10 % Loop 2
do some calculation
end
for q3=1:10 % Loop 3
do some calculation
end
end
##### 0 comentariosMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos

Iniciar sesión para comentar.

Aritra el 31 de En. de 2023
As per my understanding you are trying to execute the nested loops in random order inside the Main for Loop.
The order of execution of a for loop is linear. This behavior cannot be altered. However, you can use a randperm(n,k) function to generate a random number and the use the switch, case, otherwise expression in matlab to randomly execute a certain for loop.
To do so you can use a similar code snippet:
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
##### 7 comentariosMostrar 6 comentarios más antiguosOcultar 6 comentarios más antiguos
omar th el 25 de Feb. de 2023
@Walter Roberson thank you for your response

Iniciar sesión para comentar.

### Más respuestas (3)

Jiri Hajek el 31 de En. de 2023
Hi, use randperm function to generate the random ordering.
growingOrder = 1:10;
randomOrder = growingOrder(randperm(length(growingOrder)));
For the random calling of loops, use switch-case command:
currentLoopIndex = randomOrder(q);
switch currentLoopIndex
case growingOrder(1)
% loop 1
case growingOrder(2)
% loop 2
case growingOrder(3)
% loop 3
end
##### 1 comentarioMostrar NingunoOcultar Ninguno
omar th el 16 de Feb. de 2023
Thank you so much for your response

Iniciar sesión para comentar.

Steven Lord el 25 de Feb. de 2023
Another possible solution to the problem, if you want to run a series of functions in a loop in a random order, is to use a cell array of function handles.
The line functionsToExecute{whichFunction}() extracts one of the three function handles from the cell array functionsToExecute then calls that function handle with no input arguments. The empty parentheses are necessary to call the function rather than simply displaying the function handle.
functionsToExecute = {@function1, @function2, @function3WithLoop};
for k = 1:5
orderOfFunctions = randperm(3);
for whichFunction = orderOfFunctions
fprintf("At iteration k = %d, running function %d\n", k, whichFunction)
functionsToExecute{whichFunction}()
end
fprintf("Outer loop iteration k = %d complete!\n \n", k)
end
At iteration k = 1, running function 1
Inside function 1
At iteration k = 1, running function 2
Function 2, executing!
At iteration k = 1, running function 3
function3WithLoop executing inner loop iteration k = 1 function3WithLoop executing inner loop iteration k = 2 function3WithLoop executing inner loop iteration k = 3
Outer loop iteration k = 1 complete!
At iteration k = 2, running function 2
Function 2, executing!
At iteration k = 2, running function 1
Inside function 1
At iteration k = 2, running function 3
function3WithLoop executing inner loop iteration k = 1 function3WithLoop executing inner loop iteration k = 2 function3WithLoop executing inner loop iteration k = 3
Outer loop iteration k = 2 complete!
At iteration k = 3, running function 2
Function 2, executing!
At iteration k = 3, running function 1
Inside function 1
At iteration k = 3, running function 3
function3WithLoop executing inner loop iteration k = 1 function3WithLoop executing inner loop iteration k = 2 function3WithLoop executing inner loop iteration k = 3
Outer loop iteration k = 3 complete!
At iteration k = 4, running function 2
Function 2, executing!
At iteration k = 4, running function 3
function3WithLoop executing inner loop iteration k = 1 function3WithLoop executing inner loop iteration k = 2 function3WithLoop executing inner loop iteration k = 3
At iteration k = 4, running function 1
Inside function 1
Outer loop iteration k = 4 complete!
At iteration k = 5, running function 2
Function 2, executing!
At iteration k = 5, running function 3
function3WithLoop executing inner loop iteration k = 1 function3WithLoop executing inner loop iteration k = 2 function3WithLoop executing inner loop iteration k = 3
At iteration k = 5, running function 1
Inside function 1
Outer loop iteration k = 5 complete!
function function1
disp("Inside function 1")
end
function function2
disp("Function 2, executing!")
end
function function3WithLoop
for k = 1:3
fprintf("function3WithLoop executing inner loop iteration k = %d\n", k)
end
end
##### 0 comentariosMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos

Iniciar sesión para comentar.

Sarvesh Kale el 31 de En. de 2023
Hi omar th,
I have borrowed a part of answer from Jiri Hajek, you can acheive the random execution of loop using following lines of code
% pre define a random generated array and call it select
select = randi([1,3],1,100); % this will create a random vector whose entries will be 1, 2, or 3
for q=1:100 % MAIN LOOP
switch select(q)
case 1
for q1=1:10 % Loop 1
%do some calculation
end
case 2
for q2=1:10 % Loop 2
%do some calculation
end
case 3
for q3=1:10 % Loop 3
%do some calculation
end
end
end
##### 3 comentariosMostrar 2 comentarios más antiguosOcultar 2 comentarios más antiguos
Walter Roberson el 20 de Feb. de 2023
Do not randperm each iteration separately. Your code t = randperm(3,1) is just a slower way (in context) of executing t = randi(3) : the next q iteration, you could potentially get exactly the same t value again.
I calculate, for example, that if you ask for 5 different single-value random numbers, that roughly 39.5% of the time, at least one of the functions will not get executed. The more iterations, the lower the probability that a function will be missed, but the probability will never go to 0 if at least one iteration is done.
If you want to execute each function a minimum of a certain number of times, first construct a control vector that contains as many copies of the function index as the minimum number of executions. For example,
[1,1,2,3]
for the case where function 1 must be executed at least twice and functions 2 and 3 must be executed at least once each. Then append to that randi() of the number of functions, as many times as needed to fill out the iterations, so that after this step, the control vector is the same length as the total number of iterations. Now take
order = ControlVector(randperm(numel(ControlVector)));
for q = 1 : number_of_iterations
t = order(q);
switch t
stuff
end
end
This arrangement permits you to have different minimum number of iterations for the different functions.
If you just need to ensure that each function is executed at least once,then you can do
ControlVector = [1:NumberOfFunctions, randi(NumberOfFunctions, 1, number_of_iterations - number_of_functions)];
order = ControlVector(randperm(numel(ControlVector)));

Iniciar sesión para comentar.

### Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

R2018a

### Community Treasure Hunt

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

Start Hunting!