2

我有一个矩阵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));

但我不确定如何一次为矩阵执行此操作,并且只置换给定行中的元素。这可能吗?我可以从许多排列的向量中构造一个矩阵,但我不希望这样做。

谢谢。

4

1 回答 1

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
于 2012-11-20T16:25:29.660 回答