2013-01-02 66 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