Implementing parallel while loops in matlab.

16 views (last 30 days)
Hi all,
I am writing code that has two while loops in a random sampling exercise. I have two questions.
I would like the while loops to be performed simultaneously as opposed to the nested loops below, which does not yield the desired results. How can one modify the code to perform a parallel while loop/ simultaneously sample each of the while loops? And secondly, how can I pass the DG_uptake and DG2_uptake variables into one variable in the while loop as opposed to obtaining each one of them separately? Thank you.
while (modules_DG>=1) % number of DG
DG_PoC=randsample(MCS_nodes,1,true) % randomly select the position of DG1
while modules_DG2>=1 % number of DG2
DG2_PoC=randsample(MCS_nodes_DG2,1,true) % random selection of DG2 position
if rem(DG2_PoC,3)==0
DG2_node_pos=fix(DG2_PoC/3);
DG2_phase_pos=3;
else
DG2_phase_pos=rem(DG2_PoC,3);
DG2_node_pos=fix(DG2_PoC/3)+1;
end
DG2_uptake(DG2_node_pos,DG2_phase_pos) = DG2_uptake(DG2_node_pos,DG2_phase_pos)+ 1
if DG2_uptake(DG2_node_pos,DG2_phase_pos)> DG2_modules(DG2_node_pos,DG2_phase_pos)
DG2_uptake(DG2_node_pos,DG2_phase_pos) = DG2_uptake(DG2_node_pos,DG2_phase_pos)- 1
remove_PoC = MCS_nodes_DG2== (DG2_node_pos - 1)*3 + DG2_phase_pos; %determine the full PoC
MCS_nodes_DG2(remove_PoC) = [];%remove node from allocation array
else
modules_DG2=modules_DG2-1;
end
end
if rem(DG_PoC,3)==0
DG_node_pos=fix(DG_PoC/3);
DG_phase_pos=3;
else
DG_phase_pos=rem(DG_PoC,3);
DG_node_pos=fix(DG_PoC/3)+1;
end
DG_uptake(DG_node_pos,DG_phase_pos) = DG_uptake(DG_node_pos,DG_phase_pos)+ 1;
if DG_uptake(DG_node_pos,DG_phase_pos)> DG_modules(DG_node_pos,DG_phase_pos)
DG_uptake(DG_node_pos,DG_phase_pos) = DG_uptake(DG_node_pos,DG_phase_pos)- 1
remove_PoC = MCS_nodes== (DG_node_pos - 1)*3 + DG_phase_pos; %determine the full PoC
MCS_nodes(remove_PoC) = [];%remove node from allocation array
else
modules_DG = modules_DG - 1
end
end
  4 Comments
MarKf
MarKf on 3 Jan 2023
Edited: MarKf on 3 Jan 2023
if the length of modules_DG and modules_DG2, which are used to define the while loops, are different, one would need to know how they differ and which is the logic to create them to ascertain whether you could integrate them or not, sice they are defined outside of the loop and we have no way of knowing how and if this code runs.
It's likely you can only do it separately (if by simultaneously you mean together in the same while loop that is, otherwise you can parfor, that's real simultaneity) that is while, DG, end; while, DG2, end then. Just copy and paste the nested DG2 while loop ouside, otherwise you are repeating that nested one a lot needlessly.

Sign in to comment.

Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!