Taking a number out of a vector and not replacing it

조회 수: 2 (최근 30일)
Steven Strange
Steven Strange 2020년 3월 12일
답변: Steven Lord 2020년 3월 12일
Hello World,
Suppose I have a code, where I am choosing a number out of a set, and once that number is chosen, i dont replace it. I want to then run the code mutiple times and not replace any numbers that have been chosen. So for example say i get : 10 10 10. I want to then run the code again without the 3 tens, then again without the 3 numbers that ive drawn. so then there will be 6 numbers less, i want to carry on doing this 20 times and there should be less numbers every time that i run it.
can somebody help me please, really struggling. Thanks Steven
v = [1,2,3,4,5,6,7,8,9,10,10,10,10];
x = [v,v,v,v,v,v];
i0 = (randi(length(x)));
j0 = (randi(length(x)));
k0 = (randi(length(x)));
while j0==i0
j0 = (randi(length(x)));
end
while k0==j0
while k0==i0
k0 = (randi(length(x)));
end
if k0==j0
k0 = (randi(length(x)));
end
end
Hand1 = [x(i0),x(j0)]
Hand2 = [x(k0)]
x(i0) = 0;
x(j0) = 0;
x(k0) = 0;
x

답변 (1개)

Steven Lord
Steven Lord 2020년 3월 12일
Use randperm to generate a list of indices you can use to shuffle your list of data. Pull the first three elements from the output of randperm and use those as indices into your list of data. Next time, pull the next three elements from the output of randperm and use those as indices. Repeat this pattern until you're done or until you run out of elements.
If you know you only need a few elements from your long list of data, use the two input form of randperm to generate only as many indices as you need.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by