MATLAB: Transform a set of “if” arguments into a unified “for” function

for loop

Hello kind people,
I'm trying to optimize this segment of a function. Currently, it will give an output to the user when n_dice =< than 3.
if(n_dice==1)
Z= randi(6,1,n_trials);
end
if(n_dice==2)
Z= randi(6,1,n_trials) + randi(6,1,n_trials);
end
if(n_dice==3)
Z= randi(6,1,n_trials) + randi(6,1,n_trials) + randi(6,1,n_trials);
end
I'm trying to chage it so that it will accept any number of n_dice, maybe by using a for…? I've tried stuff like
sdice = randi(6,1,n_trials);
for i = 1:n_dice
X = sdice(i);
end
Z = sum(X)
Could you please suggest something?

Best Answer

if n_dice==1
Z=randi(6,1,n_trials);
else
Z=sum(randi(6,n_dice,n_trials));
end
Related Question