Help Creating For Loop to test PRV in every pipe (MATLAB)

I am trying to model the differences made in a leaking system by adding a pressure reducing valve in every possible location of a water distribution system, and seeing which location saves the most water or energy.
So far I have created a code that will add a PRV, remove the pipe where the PRV is added, retrieve the computed time series, then add the pipe back to its original location. I would like to transform this code into a For Loop that test every possible location of the PRV in the network. Any ideas on how to do this with the code below? My main concern is that when I add the pipe back in to the system, it does not go to the original place in the pipe index. So I’m afraid that if I ran the loop as is, some pipes would get replaced with PRV’s more than once, and some pipes may not get replaced with a PRV at all. I would also like any ideas on how to store the results from each iteration in the loop would be greatly appreciated.
%%
% Clear
clear; close(‘all’); clc;

start_toolkit;

% Load network
%set simulation duration

d = epanet(‘existing system contr.inp’);

hrs = 96;
d.setTimeSimulationDuration(hrs*3600)
%Run Hydraulic Analysis over this time
hyd_res = d.getComputedTimeSeries;
%Get Existing Pipe Data
aLinkIndex=d.getLinkPipeIndex;
LinkIndex = 5;
exlinkdiam=d.getLinkDiameter(LinkIndex);
exlinklength=d.getLinkLength(LinkIndex);
exlinkrough=d.getLinkRoughnessCoeff(LinkIndex);
exlinkminor=d.getLinkMinorLossCoeff(LinkIndex);
exlinkinitial=d.getLinkInitialStatus(LinkIndex);
conn=d.getNodesConnectingLinksID;
befNodes=conn(LinkIndex,:);
fromNode=befNodes{1};
toNode=befNodes{2};
linknames=d.getLinkPipeNameID;
linkid=linknames{LinkIndex};
d.deleteLink(LinkIndex);

%Add PRV
Code=‘PRV4’;
Vlv_Stg=20;
valve_index = d.addLinkValvePRV(Code,fromNode,toNode);
d.setLinkInitialSetting(valve_index,Vlv_Stg);

%Run Hydraulic Analysis over this time
hyd_red = d.getComputedTimeSeries;

%Add original Pipe back
newpipe=d.addLinkPipe(linkid,fromNode,toNode);
d.setLinkDiameter(LinkIndex,exlinkdiam);
d.setLinkLength(LinkIndex,exlinklength);
d.setLinkRoughnessCoeff(LinkIndex,exlinkrough);
d.setLinkInitialStatus(LinkIndex,exlinkinitial);

%unload library
d.unload;