MATLAB randomly permuting columns differently

早过忘川 提交于 2019-12-01 20:56:23

If you type open randperm (at least in Matlab R2010b) you'll see that its output p for an input M is just

[~, p] = sort(rand(1,M));

So, to vectorize this for N rows,

[~, P] = sort(rand(N,M), 2);

Thus, generate P and use linear indexing into A:

[~, P] = sort(rand(N,M), 2);
A = A(bsxfun(@plus, (1:N).', (P-1)*N));

Example: given

N = 3;
M = 4;
A = [ 1     2     3     4
      5     6     7     8
      9    10    11    12 ];

one (random) result is

A =
     2     3     1     4
     7     5     8     6
     9    11    12    10
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!