置换矩阵行内的元素

时间:2012-11-20 16:09:35

标签: matlab matrix element permutation

我有一个矩阵 A

A = [0 0 0 0 1; 0 0 0 0 2; 0 1 2 3 4];

我想随机置换每一行中的元素。例如,矩阵 A2

A2 = [1 0 0 0 0; 0 0 0 2 0; 4 1 3 2 0]; % example of desired output

我可以用矢量来做到这一点:

Av = [0 1 2 3 4];
Bv = Av(randperm(5));

但我不确定如何在矩阵中连续执行此操作,并且只对给定行中的元素进行置换。这可能吗?我可以用许多置换向量构造一个矩阵,但我不想这样做。

感谢。

1 个答案:

答案 0 :(得分:6)

您可以在任意大小的随机数组上使用sort(这是randperm所做的)。在那之后,你需要做的就是一些索引技巧来正确地重新调整数组

A = [0 0 0 0 1; 0 0 0 0 2; 0 1 2 3 4];
[nRows,nCols] = size(A);

[~,idx] = sort(rand(nRows,nCols),2);

%# convert column indices into linear indices
idx = (idx-1)*nRows + ndgrid(1:nRows,1:nCols);

%# rearrange A
B = A;
B(:) = B(idx)

B =

     0     0     1     0     0
     0     2     0     0     0
     2     1     3     4     0