Effacer les filtres
Effacer les filtres

randomly select elements of an array

212 vues (au cours des 30 derniers jours)
Noe alvarado
Noe alvarado le 12 Avr 2012
Commenté : Steven Lord le 7 Fév 2022
Hi How i can select randomly elements from a matrix o array
I have the matrix and i want to select "x" numbers of elements
thanks

Réponse acceptée

Walter Roberson
Walter Roberson le 12 Avr 2012
msize = numel(YourMatrix);
idx = randperm(msize);
YourMatrix(idx(1:x))
If you have a fairly new version of MATLAB, you can instead use
msize = numel(YourMatrix);
YourMatrix(randperm(msize, x))
  10 commentaires
Jaime Gurrola
Jaime Gurrola le 7 Déc 2020
Hi walter, i want to select a random element from this array, help please
A={'Yellow','Green','Blue','Orange','Black','Grey','Red','Brown','Purple','White'};
Walter Roberson
Walter Roberson le 3 Sep 2021
A{randi(numel(A))}

Connectez-vous pour commenter.

Plus de réponses (2)

Prasobhkumar P. P.
Prasobhkumar P. P. le 28 Juil 2020
Modifié(e) : Walter Roberson le 3 Sep 2021
histHandle= histfit(data,nBins,'normal');
[Val Ind] = max(histHandle(2).YData); %histHandle(2) corresponds to the curve fitted
M = histo18(2).XData(Ind);

Adam Wyatt
Adam Wyatt le 3 Sep 2021
Modifié(e) : Adam Wyatt le 3 Sep 2021
Use "randsample"
For array:
Arry = [1 4 5 7 8 9];
Smpl = randsample(Arry, 3)
Smpl = 1×3
9 5 4
For strings:
Arry = ["Yellow" "Green" "Blue" "Orange" "Black" "Grey" "Red" "Brown" "Purple" "White"];
Smpl = randsample(Arry, 2)
Smpl = 1×2 string array
"Purple" "Brown"
How do you want to sample the matrix? If its any element, just convert to array (e.g. Mat(:)). Otherwise you have to apply the function to each row/column separately.
  3 commentaires
Piyush Kant
Piyush Kant le 7 Fév 2022
Is there any method/parameter with which we can reproduce same random series so that the different algorithms can be evaluated? I know that way it wont be a random series anymore still the psudorandomness can be helpful for multiple runs.
Steven Lord
Steven Lord le 7 Fév 2022
See the "Control Random Number Generation" topic on this documentation page.
Some older functions that use random numbers internally (like eigs, which generates a starting point at random if one is not given to it) have the ability to specify inputs that avoid the randomness (in the case of eigs by specifying v0 in the options structure or specifying the StartVector name-value pair argument.)

Connectez-vous pour commenter.

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by