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.

Answers (2)

madhan ravi
madhan ravi on 29 Dec 2018
Edited: madhan ravi on 29 Dec 2018
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 Comments

Stephen23
Stephen23 on 29 Dec 2018
Edited: Stephen23 on 29 Dec 2018
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.
If you allow duplication, that's ok. But if not, I would recommend using randperm function.

Sign in to comment.

Stephen23
Stephen23 on 29 Dec 2018
Edited: Stephen23 on 29 Dec 2018
Use randperm to generate a random permutation of that vector:
>> T = [0,1,2,7,71,158,187];
>> A = T(randperm(numel(T)))
A =
1 187 158 0 7 71 2

Categories

Find more on Random Number Generation in Help Center and File Exchange

Asked:

on 29 Dec 2018

Edited:

on 29 Dec 2018

Community Treasure Hunt

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

Start Hunting!