How to randomly interchange values in different rows in a matrix
1 回表示 (過去 30 日間)
古いコメントを表示
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
0 件のコメント
採用された回答
その他の回答 (1 件)
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).';
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!