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.
0 个评论
采纳的回答
David Hill
2022-9-25
A=[1,2,3 ; 7,8,9 ; 13,14,15];
perms_of_(A,2)
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
0 个评论
更多回答(1 个)
Walter Roberson
2022-9-25
A=[1,2,3 ; 7,8,9 ; 13,14,15]
perms_of_(A)
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!