choose elements from array randomly
16 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi everyone
I have vector array of elements …
for example a=[1,2,3,4]
how can I choose randomly 10% of the above array????
Help me please
majid
0 commentaires
Réponse acceptée
Wayne King
le 23 Sep 2012
You must be using an older version of MATLAB, do this instead:
% create vector
a = randn(100,1);
% determine how many elements is ten percent
numelements = round(0.1*length(a));
% get the randomly-selected indices
indices = randperm(length(a));
indices = indices(1:numelements);
% choose the subset of a you want
b = a(indices);
Plus de réponses (2)
Azzi Abdelmalek
le 23 Sep 2012
Modifié(e) : Azzi Abdelmalek
le 23 Sep 2012
a=[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17]
n=length(a)
nr=round(n/10)
out=a(randperm(n,nr))
or if you have'nt randperm
n=length(a);
nr=round(n/10)
[ ~,idx]=sort(rand(n,1));
out=a(idx(1:nr))
1 commentaire
Azzi Abdelmalek
le 23 Sep 2012
Depends on how you want to round your percentage use, round or ceil or floor
Wayne King
le 23 Sep 2012
Modifié(e) : Wayne King
le 23 Sep 2012
One thing you can do is:
% create vector
a = randn(100,1);
% determine how many elements is ten percent
numelements = round(0.1*length(a));
% get the randomly-selected indices
indices = randperm(length(a),numelements);
% choose the subset of a you want
b = a(indices);
2 commentaires
Wayne King
le 23 Sep 2012
See my answer below for a use of randperm compatible with earlier versions of MATLAB
Voir également
Catégories
En savoir plus sur Get Started with MATLAB dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!