在MATLAB中置换矩阵的列

时间:2016-01-26 14:48:31

标签: matlab matrix random permutation vectorization

假设我有一个n by d矩阵A,我想要置换某些列的条目。为此,我将1 ... n的排列计算为

idx1 = randperm(n)'
idx2 = randperm(n)'

然后我可以做:

A(:,1) = A(idx1,1)
A(:,2) = A(idx2,2)

但是,我不想使用for循环来执行此操作,因为它会很慢。假设我有一个n by d矩阵A和一个n by d索引矩阵IDX来指定排列,是否有更快的等效于以下for循环:

for i = 1:d
    A(:,i) = A(IDX(:,i),i);
end

2 个答案:

答案 0 :(得分:4)

linear-indexing -

的帮助下使用bsxfun
[n,m] = size(A);
newA = A(bsxfun(@plus,IDX,[0:m-1]*n))

答案 1 :(得分:0)

我想另一个相当愚蠢的方法就是cellfun,愚蠢因为你必须将它转换成一个单元格然后将其转换回来,但它仍然存在。

N=ones(d,1)*n; %//create a vector of d length with each element = n
M=num2cell(N); %//convert it into a cell
P=cellfun(@randperm, M,'uni',0); %//cellfun applys randperm to each cell
res = cell2mat(P); %//Convert result back into a matrix (since results are numeric).

这也允许使用Char和String类型的randperm,但是cell2mat不适用于那些情况,结果是Cell Array格式。

for d = 5, n = 3:
>> res =

 1     3     2
 1     2     3
 2     3     1
 3     1     2
 3     2     1