How can I keep values of an array random.
이전 댓글 표시
I have an array T=(0 1 2 7 71 158 187).
i wanna generate A=(158 71 2 187 0 152 1)
please tell me a command for generating A.
답변 (2개)
madhan ravi
2018년 12월 29일
편집: madhan ravi
2018년 12월 29일
Note : In your desired result A there appears a number 152 instead of 7 which I guess is perhaps a typo.
Just use random indexing using randperm() or randsample() so that the indices are unique not repeated :
A = T(randperm(numel(T)))
%or
A = T(randsample(numel(T),numel(T)))
Will just leave this here : (Reason: People shouldn't think I edited my answer after the comments below so here is the proof)


댓글 수: 2
Note that randi can repeat values, and therefore repeats/misses values of T in the output. This might not be the desired effect (and is not shown in the example).
See my answer for a simple random permutation of the values of T, without any repetition.
Akira Agata
2018년 12월 29일
If you allow duplication, that's ok. But if not, I would recommend using randperm function.
>> T = [0,1,2,7,71,158,187];
>> A = T(randperm(numel(T)))
A =
1 187 158 0 7 71 2
카테고리
도움말 센터 및 File Exchange에서 Random Number Generation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!