2013-01-02 65 views
2

我正在循環一個數組,多次使用,每次重新啓動數組時都會更改順序(使用randperm)。MATLAB數字循環

我的問題是,有時我得到的東西像下面我數組的順序:

1 3 5 6 8 7 2 4 9  
9 4 2 7 8 6 5 3 1 

注意,第一陣列循環的終點是一樣的下一個數組循環的開始。有什麼辦法可以控制這個嗎?

我已經嘗試在循環結束之前放置rng (n)randn(n),然後再回到隨機化順序並繼續循環,但這沒有幫助。

編輯 - 代碼

for b = 1; 
while b <= 2 
    for n = randperm(length(V)); 
    disp(V {n}); 
    end 
b = b+1; 
end 
end 
+5

您可以檢查此條件,重新隨機化(如果存在)。 – ja72

+1

你可以請你發佈你的代碼中包含循環的部分? –

+0

剛剛在上面添加了它。 –

回答

3

下面是實現ja72的建議很短的解決方案:

V = 1:9; 
b = 1; 
while b <= 10 
    nextperm = randperm(length(V)); %// Generate a random permutation 

    %// Verify permutation 
    if (b > 1 && nextperm(1) == prevperm(end)) 
     continue 
    end 
    prevperm = nextperm; 

    disp(V(nextperm)); 
    b = b + 1; 
end 
+1

使用'randperm()以及用於實現解決方案的幾行代碼:) – bonCodigo

1

我覺得這是你所需要的,沉澱在隨機置換前的檢查條件?

matrix = [11,22,33,44,55,66,77,88,99]; 
randOrder = zeros(length(matrix)); 
randOrderIntermediate = zeros(length(matrix)); 
randOrderPrev = zeros(length(matrix)); 

for i = 1:10 

%Store the previous random order 
randOrderPrev = randOrder; 
%Create interim random order 
randOrderIntermediate = randperm(length(matrix)); 
%check condition, is the first the same as the previous end? 
while randOrderIntermediate(end) == randOrderPrev(1) 
    %whilst condition true, re-randomise 
    randOrderIntermediate = randperm(length(matrix)); 
end 
%since condition is no longer true, set the new random order to be the 
%intermediate one 
randOrder = randOrderIntermediate; 

%As with your original code. 
for n = randOrder 
    disp(matrix(n)) 
end 

end