How to create a random array from an array
    9 views (last 30 days)
  
       Show older comments
    
Hello every one 
I have a 1x450 array and I want to choose 300 elements of this array randomly and create a new array with random elements 
I tried randi and randperm but these two didn't give me the answer I want 
What should I use instead
Thanks in advance
2 Comments
  Dyuman Joshi
      
      
 on 16 Feb 2023
				What did you try?
Do you want 300 different indices? or 300 indices with repetitions works?
  Jan
      
      
 on 16 Feb 2023
				randi creates indices with repetitions, randperm without. If both methods are not working for you, the problem is hidden inside "didn't give me the answer I want". The readers cannot guess, what you have exactly tried and what you want. So please post your code and explain, what you want to change.
Accepted Answer
  Arif Hoq
      
 on 16 Feb 2023
        try this:
A=randi(500,1,450);
B=A(randperm(numel(A),300));% choose 300 elements randomly
2 Comments
  Steven Lord
    
      
 on 16 Feb 2023
				As Jan said, randi draws with replacement and so may generate the same number more than once. randperm draws without replacement and so won't.
rng default % for reproducibility
x = randi(10, 1, 5)
y = randperm(10, 5)
The number 10 does appear in x twice. If we use the analogy of a deck of cards, in x I selected five cards, replacing each one back in the deck after I've noted what it was. In y I dealt out a hand of five cards without putting any back on the deck.
Note that using y to index into another array may produce the same number repeatedly in that result if the array you're indexing into contains that number more than once. In the deck analogy:
deck = repmat(1:13, 4, 1)
suits = repmat(["club"; "diamond"; "heart"; "spade"], 1, 13)
cards = deck(y)
cardsuits = suits(y)
The first 1 in y corresponds to the Ace of hearts and the second corresponds to the Ace of clubs. If you only wanted to draw at most one of each rank of card (at most one Ace or at most one Queen, for example, regardless of suit) then that would require a little modification.
More Answers (0)
See Also
Categories
				Find more on Number Theory in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



