how vectorize following matlab code, performs permutation of each row of matrix r indices in corresponding row of matrix p?
for = 1:size(p,1) pp(i,:) = r(i,p(i,:)); end
example:
p = [3 2 1; 3 1 2; 2 3 1; 2 1 3; 1 2 3; 1 3 2] r = [6 5 4; 6 4 5; 5 6 4; 5 4 6; 4 5 6; 4 6 5]
produce following matrix pr:
4 5 6 5 6 4 6 4 5 4 5 6 4 5 6 4 5 6
one approach bsxfun
-
nrows = size(r,1) pp = r(bsxfun(@plus,[1:nrows]',(p-1)*nrows))
or ndgrid
-
[m,n] = size(r) pp = r(sub2ind([m n],ndgrid(1:m,1:n),p))
or replace ndgrid(1:m,1:n)
repmat
: repmat([1:m]',[1 n])
or meshgrid
:meshgrid(1:m,1:n).'
.
Comments
Post a Comment