How to permute elements of jth column of a matrix iteratively

3 views (last 30 days)
I am trying to write a 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);
for i = 1:d
A(:,i) = A(randperm(n),i)
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.

Accepted Answer

David Hill
David Hill on 25 Sep 2022
A=[1,2,3 ; 7,8,9 ; 13,14,15];
perms_of_(A,2)
ans =
ans(:,:,1) = 1 14 3 7 8 9 13 2 15 ans(:,:,2) = 1 14 3 7 2 9 13 8 15 ans(:,:,3) = 1 8 3 7 14 9 13 2 15 ans(:,:,4) = 1 8 3 7 2 9 13 14 15 ans(:,:,5) = 1 2 3 7 14 9 13 8 15 ans(:,:,6) = 1 2 3 7 8 9 13 14 15
function A_perms = perms_of_(A,j)
p=perms(A(:,j));
for i = 1:length(p)
A_perms(:,:,i)=A;
A_perms(:,j,i) = p(i,:)';
end
end

More Answers (1)

Walter Roberson
Walter Roberson on 25 Sep 2022
A=[1,2,3 ; 7,8,9 ; 13,14,15]
A = 3×3
1 2 3 7 8 9 13 14 15
perms_of_(A)
ans =
ans(:,:,1) = 1 2 3 7 8 9 13 14 15 ans(:,:,2) = 1 14 3 7 2 9 13 8 15 ans(:,:,3) = 1 2 15 7 8 3 13 14 9
function perms = perms_of_(A)
[rows, cols] = size(A);
perms = repmat(A, 1, 1, cols);
for i = 1 : cols
perms(:,i,i) = A(randperm(rows),i);
end
end
The result is a 3D matrix with as many planes as there are columns. In the K'th plane, the K'th column is the one permuted.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!