2016-09-30 71 views
1

我有以下矢量 a = 3 3 5 5 20 20 20 4 4 4 2 2 2 10 10 10 6 6 1 1 1 有誰知道如何洗牌這個載體與相同的元素永遠不會分開? 像波紋管 a = 10 10 10 5 5 4 4 4 20 20 20 1 1 1 3 3 2 2 2 6 6 謝謝你,最好的方面...matlab洗牌元素的矢量具有相同的序列相同的數字

+0

這些羣體總是保證是唯一的,你不會有:'3 3 5 5 3 3 4 4'? – Suever

+0

是我有這個矩陣firts a = [3 2; 5 2; 20 3; 4 3; 2 3; 10 3; 6 2; 1 3] 我做了一些事情,我的矩陣變成: a = [3 2; 3 2; 5 2; 5 2; 20 3; 20 3; 20 3; 4 3; 4 3; 4 3; 2 3; 2 3; 2 3; 10 3; 10 3; 10 3; 6 2; 6 2; 1 3; 1 3; 1 3] 現在我需要隨機的第一行的值... – 8727

回答

3

您可以使用uniqueaccumarray相結合,創造每個組值放入一個單獨的電池單元的單元陣列。然後你可以洗牌這些元素並將它們重新組合成一個數組。

% Put each group into a separate cell of a cell array 
[~, ~, ind] = unique(a); 
C = accumarray(ind(:), a(:), [], @(x){x}); 

% Shuffle it 
shuffled = C(randperm(numel(C))); 

% Now make it back into a vector 
out = cat(1, shuffled{:}).'; 

% 20 20 20 1 1 1 3 3 10 10 10 5 5 4 4 4 6 6 2 2 2 

另一種選擇是使用unique得到的值,然後計算使每個出現的數目。然後,您可以洗牌的價值和使用repelem拓展出來的結果

u = unique(a); 
counts = histc(a, u); 

% Shuffle the values 
inds = randperm(numel(u)); 

% Now expand out the array 
out = repelem(u(inds), counts(inds)); 
+0

非常感謝你的作品太.. – 8727

3

一個非常類似的答案@Suever,使用循環和邏輯矩陣,而不是細胞

a = [3 3 5 5 20 20 20 4 4 4 2 2 2 10 10 10 6 6 1 1 1]; 

vals = unique(a); %find unique values 
vals = vals(randperm(length(vals))); %shuffle vals matrix 

aout = []; %initialize output matrix 
for ii = 1:length(vals) 
    aout = [aout a(a==(vals(ii)))]; %add correct number of each value 
end 
+0

非常感謝你@伊利萊利... – 8727

3

這裏的另一種方法:

a = [3 3 5 5 20 20 20 4 4 4 2 2 2 10 10 10 6 6 1 1 1]; 
[~, ~, lab] = unique(a); 
r = randperm(max(lab)); 
[~, ind] = sort(r(lab)); 
result = a(ind); 

實施例的結果:

result = 
    2 2 2 3 3 5 5 20 20 20 4 4 4 10 10 10 1 1 1 6 6 

它的工作原理如下:

  1. 指定獨特標籤的a每個元素根據它們的值(這是矢量lab);
  2. lab的值應用於自身的隨機雙射(其隨機雙射由r表示;應用它的結果是r(lab));
  3. 排序r(lab)並獲得排序的指數(這是ind);
  4. 將這些指數應用於a
相關問題