How to randomly interchange values in different rows in a matrix

1 回表示 (過去 30 日間)
SM Hsu
SM Hsu 2019 年 3 月 5 日
コメント済み: SM Hsu 2019 年 3 月 11 日
Hello,
I have a matrix, say A = [1 2 3 4 5;6 7 8 9 10]. I would like to randomly pick a cutpopint for each row and then swap the elements. Here is my script:
for row = 1:size(A,1)
cutpoint = randsample(size(A,2),1);
B(row,:) = A(row, [cutpoint:end 1:cutpoint-1]);
end
I was wondering if there is a neat way to skip to the loop, because my matrix is huge and I have to repeat the cut-and-swap procedure on the matrix 1000 times. This is really time consuming.
Any help is much appreciated.
Best,
Shen-Mou

採用された回答

Matt J
Matt J 2019 年 3 月 5 日
編集済み: Matt J 2019 年 3 月 5 日
[m,n] = size(A);
shuffle=mod( randi([0,n-1],m,1)+(0:n-1) , n )*m +(1:m).',
B=A(shuffle),
  7 件のコメント
Matt J
Matt J 2019 年 3 月 6 日
編集済み: Matt J 2019 年 3 月 6 日
You should upgrade your Matlab version to avoid that and to simplify your code, but if you cannot upgrade then you can re-implement as follows
z = bsxfun(@plus, randi([0,n-1],m,1) , (0:n-1) );
shuffle=bsxfun(@plus, mod(z,n)*m , (1:m).') ;
SM Hsu
SM Hsu 2019 年 3 月 11 日
Sincerly thank you again!

サインインしてコメントする。

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2019 年 3 月 5 日
編集済み: Andrei Bobrov 2019 年 3 月 5 日
[m,n] = size(A);
At = A.';
[~,ii] = sort(rand([n,m]));
cutpoint = find(ii == 1);
i0 = zeros([n,m]);
i0(1,:) = 1;
i0(ccutpoint) = -1;
I = cumsum(i0);
I(:,I(1,:) == -1) = 0;
[~,ii] = sort(I);
B = At(ii + (0:m-1)*n).';

カテゴリ

Help Center および File ExchangeAutomotive についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by