Transform a set of "if" arguments into a unified "for" function

1 visualizzazione (ultimi 30 giorni)
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?

Risposta accettata

David Hill
David Hill il 2 Nov 2019
if n_dice==1
Z=randi(6,1,n_trials);
else
Z=sum(randi(6,n_dice,n_trials));
end

Più risposte (1)

KALYAN ACHARJYA
KALYAN ACHARJYA il 2 Nov 2019
n_trials=?? % define n_trials
n_dice=randi(6,1,n_trials);
Z=n_dice*randi(6,1,n_trials);

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by