Function that pulls a name from a list at random but doesn't repeat
Mostrar comentarios más antiguos
I'm working on a two-part assignment that requires a function to pick a random index from a list of names. The function itself needs to check if the index has been pulled before so that it doesn't repeat any names. This is what I have so far,
function name = pick_name(list)
persistent ind_picked
n_picked = length(ind_picked);
n_list = length(list);
if isempty(n_picked)
ind = randi(n_list);
ind_picked = ind;
name = list(ind);
else
while found == find(ind_picked==ind)
ind = randi(n_list);
ind_picked = [ind_picked,ind];
end
name = list(ind);
end
What am I doing wrong??
4 comentarios
David Fletcher
el 14 de Abr. de 2018
You could just use randperm(length(list)) to give you a vector of non-repeating random indices from 1 to the length of the list. You could then just sequentially use the values from this index list
Matt Rulli
el 14 de Abr. de 2018
David Fletcher
el 14 de Abr. de 2018
Editada: David Fletcher
el 14 de Abr. de 2018
All those variables that you are carefully declaring in the if condition on the first call of the function will go out of scope when the function exits (the condition on the if statement is slightly iffy as well - shouldn't it be if n_picked==0). On the second call because n_picked is persistent and no longer has a length of 0all those variables declared in the if condition won't execute and so ind won't exist when you are trying to use it in the while condition of your else statement (where is found defined btw). It might be worth detailing what your 'prescribed steps' are exactly. It will always be harder to pick a number that doesn't exist in a list of numbers that have already been picked rather than remove a number from a list of numbers that haven't already been picked.
Matt Rulli
el 14 de Abr. de 2018
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Matrix Indexing en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
