Resolving Matrix Columns in MATLAB

Say I have a matrix n by d Aand I want to rewrite the entries in some columns. For this, I compute the permutations 1 ... nas

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

Then I could do:

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

However, I do not want to do this with for-loop, as it will be slow. Say I have a matrix n by d Aand an index matrix n by d IDXthat defines permutations, there is a faster equivalent to the following for-loop:

for i = 1:d
    A(:,i) = A(IDX(:,i),i);
end
+4
source share
2 answers

Using linear-indexingwith bsxfun-

[n,m] = size(A);
newA = A(bsxfun(@plus,IDX,[0:m-1]*n))
+4
source

, 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).

randperm Char String, cell2mat , .

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

 1     3     2
 1     2     3
 2     3     1
 3     1     2
 3     2     1
0

Source: https://habr.com/ru/post/1626013/


All Articles