Why do it in a complicated way, using loops and if statements?
d = randi(6,[1 5])
d =
4 1 6 6 5
rerolls = [1 2 5];
d(rerolls) = randi(6,[1 numel(rerolls)])
d =
5 5 6 6 3
Note that IF rerolls is an empty vector, then nothing should change. Does that work here?
rerolls = [];
d(rerolls) = randi(6,[1 numel(rerolls)])
d =
5 5 6 6 3
Yep.
You still need to decide which dice to re-roll, but that is your problem.