How to sort the elements of a matrix in a random order
1 回表示 (過去 30 日間)
古いコメントを表示
I have three matrix
A=[4,5,8,1,6,3]', B =[1,2,3,7,9,6]' and C=[3,1,2,4,7,9]'
and I want to generate X=[A B C] such that each element in A,B,C is randomly placed. I amusing Matlab 2007b
2 件のコメント
Azzi Abdelmalek
2012 年 8 月 28 日
each element in A,B,C is randomly placed before or after concatenation?
採用された回答
Sean de Wolski
2012 年 8 月 28 日
編集済み: Sean de Wolski
2012 年 8 月 28 日
So you want each column to be sorted randomly but to still be in the column it came from?
A=[4,5,8,1,6,3]';
B=[1,2,3,7,9,6]';
C=[3,1,2,4,7,9]';
ABC = [A B C]; %concatenate
[~,idx] = sort(rand(size(ABC))); %random indexes
ABCrand = ABC(bsxfun(@plus,idx,0:size(ABC,1):(numel(ABC)-1))) %keep columns aligned
If you don't care about elements staying in their columns, just use randperm. Of course you could always use a for-loop with randperm above, but I won't miss any opportunity to insert a bsxfun somewhere :)
2 件のコメント
Sean de Wolski
2012 年 8 月 28 日
If you are on 2007b then you probably need a junk value instead of a '~'
[junk,idx] = sort(rand(size(ABC))); %random indexes
その他の回答 (3 件)
Matlabbey
2012 年 8 月 28 日
maybe you could try making a new random matrix and sorting by those values.
0 件のコメント
Azzi Abdelmalek
2012 年 8 月 28 日
編集済み: Azzi Abdelmalek
2012 年 8 月 28 日
A=[4,5,8,1,6,3]', B =[1,2,3,7,9,6]', C=[3,1,2,4,7,9]'
nA=length(A);
a1=perms(1:nA);nA1=size(a1,1);
res=[A(a1(round(nA1*rand(1,1)),:)); B(a1(round(nA1*rand(1,1)),:)); C(a1(round(nA1*rand(1,1)),:))]
2 件のコメント
Andrei Bobrov
2012 年 8 月 28 日
abc = [A,B,C]
[~,idx] = sort(rand(size(abc)))
out = abc(sub2ind(size(abc),idx,ones(size(abc,1),1)*(1:size(abc,2))));
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!