Permute values in a specific column of a matrix

Viewed 11

I am trying to write a MATLAB function which performs some calculations on a data set A. I want the function to return d (number of dimensions of A) matrices like A but with the jth column elements permuted:

A=[1,2,3 ; 7,8,9 ; 13,14,15]
perms_of_(A)
function perms = perms_of_(A)
    [n,d]=size(A);               % number of rows and columns
    for j = 1:d                  % permute the elements of column j
        A(:,j) = A(randperm(n),j)
    end
end

I want matrices like:

A=[7,2,3 ; 1,8,9 ; 13,14,15]
A=[1,14,3 ; 7,2,9 ; 13,8,15]
A=[1,2,9 ; 7,8,3 ; 13,14,15]

But instead I get:

A=[7,2,3 ; 1,8,9 ; 13,14,15]
A=[7,14,3 ; 1,2,9 ; 13,8,15]
A=[7,14,15 ; 1,2,9 ; 13,8,3]

In other words, I want matrices exactly like the ORIGINAL matrix A but with JUST the jth column permuted. Somehow at the beginning of each iteration I need the matrix A to be reset to the original matrix defined outside the function. The permutations on column j-1,...,1 are appearing in output j (if my wording makes sense).

1 Answers

I'm not sure I quite understand the question, but I think what you want to do is collect the d permuted matrices in a cell array like so:

function perms = perms_of_(A)
    [n,d] = size(A);
    perms = cell(d,1);
    for j = 1:d
        perms{j} = A;
        perms{j}(:,j) = A(randperm(n),j);
    end
end
Related