How to permute elements of jth column of a matrix iteratively

3 次查看(过去 30 天)
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.

采纳的回答

David Hill
David Hill 2022-9-25
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

更多回答(1 个)

Walter Roberson
Walter Roberson 2022-9-25
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.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by