Eri*_*345 4 random matlab permutation matrix vectorization
Say I have an n by d
matrix A
and I want to permute the entries of some columns. To do this, I compute permutations of 1 ... n
as
idx1 = randperm(n)'
idx2 = randperm(n)'
Run Code Online (Sandbox Code Playgroud)
Then I could do:
A(:,1) = A(idx1,1)
A(:,2) = A(idx2,2)
Run Code Online (Sandbox Code Playgroud)
However, I dont want to do this using a for
-loop, as it'll be slow. Say I have an n by d
matrix A
and an n by d
index matrix IDX
that specifies the permutations, is there a quicker equivalent of the following for
-loop:
for i = 1:d
A(:,i) = A(IDX(:,i),i);
end
Run Code Online (Sandbox Code Playgroud)
Using linear-indexing
with the help of bsxfun
-
[n,m] = size(A);
newA = A(bsxfun(@plus,IDX,[0:m-1]*n))
Run Code Online (Sandbox Code Playgroud)