我循环一个数组,多次在每次重新启动数组时更改顺序(使用randperm)。
我的问题是我偶尔得到类似下面的内容:
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
答案 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 :(得分: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