【问题标题】:Permute elements within rows of matrix置换矩阵行中的元素
【发布时间】:2012-11-20 16:09:34
【问题描述】:

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

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

谢谢。

【问题讨论】:

    标签: matlab matrix element permutation


    【解决方案1】:

    您可以在任意大小的随机数组上使用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
    

    【讨论】:

    • 请注意,对于旧版本的 matlab,您可以通过将 ~ 替换为 XXX 来使其工作
    • 谢谢@Jonas。我肯定需要更多地了解索引及其技巧。
    猜你喜欢
    • 2017-05-09
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多