【问题标题】:MATLAB Number loopingMATLAB 数字循环
【发布时间】:2013-01-02 16:01:46
【问题描述】:

我正在循环一个数组,多次循环,每次数组重新启动时都会更改顺序(使用 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

【问题讨论】:

  • 您可以检查这种情况,如果存在则重新随机化。
  • 能否请您发布包含循环的代码部分?
  • @MarkHughes 题外话:外部的for 循环似乎是多余的,因为它只为b=1 执行了一次迭代(所以它几乎不能称为“循环”)

标签: matlab loops


【解决方案1】:

这是一个实现 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() 以及几行代码来实现解决方案:)
【解决方案2】:

我认为这是您需要的,在确定随机排列之前的检查条件?

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多