Shuffle a vector of repeated numbers so the numbers do not repeat

2 vues (au cours des 30 derniers jours)
Yue Zhang
Yue Zhang le 15 Août 2016
Hi,
I have a vector fam1_1 = [1,1,1,2,2,2,3,3,3,4,4,4] that I need shuffled without having any numbers be repeated. Does anyone have any suggestions on how to do this?
  1 commentaire
Image Analyst
Image Analyst le 15 Août 2016
In general this is not possible. It's possible for that specific vector, but not in general for any arbitrary vector. For example if fam1_1 were equal to [1,1,1,2,2,1,1,1,1,1,1] it would not be possible to shuffle without repeating a 1. Just want to make sure you realize that.

Connectez-vous pour commenter.

Réponse acceptée

Azzi Abdelmalek
Azzi Abdelmalek le 15 Août 2016
Modifié(e) : Azzi Abdelmalek le 15 Août 2016
Edit
fam1_1 = [1,1,1,2,2,2,3,3,3,4,4,4]
ii=unique(fam1_1)
n=numel(fam1_1)
m=numel(ii)
p=numel(fam1_1)/numel(ii)
x=ii(randperm(m))
out=x
for k=2:p
y=setdiff(ii,x(end))
y1=y(randi(m-1))
y2=setdiff(ii,y1)
x=[y1 y2(randperm(m-1))]
out=[out x]
end
  5 commentaires
Azzi Abdelmalek
Azzi Abdelmalek le 15 Août 2016
Look at the edited answer
Yue Zhang
Yue Zhang le 15 Août 2016
that works! thank you very much :)

Connectez-vous pour commenter.

Plus de réponses (1)

Image Analyst
Image Analyst le 15 Août 2016
Like I said above, in general it's not possible, but it might be able to be solved for a particular sample. For the sample you gave, here's one solution that solves it in just 2 simple lines of code.:
fam1_1 = [1,1,1,2,2,2,3,3,3,4,4,4] % Original data
temp = reshape(fam1_1, [], 4)' % Reshape into 2D matrix
fam1_1 = temp(:)' % Turn into column vector then transpose into row vector like the original.

Community Treasure Hunt

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

Start Hunting!

Translated by