How to permute elements of jth column of a matrix iteratively

2 ビュー (過去 30 日間)
Darren
Darren 2022 年 9 月 25 日
回答済み: David Hill 2022 年 9 月 25 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by