choose elements from array randomly

조회 수: 147 (최근 30일)
Majid Al-Sirafi
Majid Al-Sirafi 2012년 9월 23일
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

채택된 답변

Wayne King
Wayne King 2012년 9월 23일
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);

추가 답변 (2개)

Azzi Abdelmalek
Azzi Abdelmalek 2012년 9월 23일
편집: Azzi Abdelmalek 2012년 9월 23일
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
Azzi Abdelmalek
Azzi Abdelmalek 2012년 9월 23일
Depends on how you want to round your percentage use, round or ceil or floor

댓글을 달려면 로그인하십시오.


Wayne King
Wayne King 2012년 9월 23일
편집: Wayne King 2012년 9월 23일
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
Majid Al-Sirafi
Majid Al-Sirafi 2012년 9월 23일
thank you dear
but when I run this code the following error had been occured
??? Error using ==> randperm Too many input arguments.
majid
Wayne King
Wayne King 2012년 9월 23일
See my answer below for a use of randperm compatible with earlier versions of MATLAB

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by