2

我正在循环一个数组,多次循环,每次数组重新启动时都会更改顺序(使用 randperm)。

我的问题是,有时我的数组顺序如下所示:

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

请注意,第一个数组循环的结束与下一个数组循环的开始相同。有没有办法控制这个?

我曾尝试在循环结束之前放置rng (n)and ,然后再返回以随机化顺序并继续循环,但这无济于事。randn(n)

编辑 - 代码

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

2 回答 2

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
于 2013-01-02T18:18:01.987 回答
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
于 2013-01-02T17:31:27.657 回答