Function that pulls a name from a list at random but doesn't repeat

조회 수: 13 (최근 30일)
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
David Fletcher
David Fletcher 2018년 4월 14일
편집: David Fletcher 2018년 4월 14일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

David Fletcher
David Fletcher 2018년 4월 14일
편집: David Fletcher 2018년 4월 14일
listNames={'a','b','c','d','e','f','g','n','h'}
for iter=1:9
name=pick_name(listNames)
end
function name = pick_name(list)
persistent ind_picked
candidate=randi(length(list));
if isempty(ind_picked)
%Initialize persistent variable with random index
ind_picked=candidate;
else
%look for int that is not already in the list
while any(candidate==ind_picked)
candidate=randi(length(list));
end
ind_picked=[ind_picked candidate];
end
name=list{candidate};
end
Some things you may want to consider and make improvements: something bad happens if you call the function and all items in the list have already been picked. Maybe there should also be a way to 'reset' the function so it forgets it's internal list of picked indexes. Personally, I would also clearly state why this is a bad approach to the problem, and that the while loop could be eliminated, and the code much simplified by instead maintaining a list of indexes that had not been picked.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by