随机交换矩阵的列:Matlab



假设

A = [1 2 3 5 7 9
     6 5 0 3 2 3]

我想随机化矩阵列的位置;这样给出B

B = [3 9 1 7 2 5
     0 3 6 2 5 3]

我该如何做这个Matlab?

尝试

B = A(randperm(length(A)))

有关说明,请参阅文档。

现在代码已经正确格式化,很明显OP希望保留列,尽管randperm仍然是HPM给出的最简单的选项。

idx = randperm(size(A,2)); % Create list of integers 1:n, in random order, 
                           % where n = num of columns
B = A(:, idx);             % Shuffles columns about, on all rows, to indixes in idx

您需要使用randperm函数生成列索引的随机排列(从1到A中的列数),然后可以使用对A进行索引

B = A(:, randperm(size(A, 2)));

最新更新