randomly select elements of an array

조회 수: 823(최근 30일)
Noe alvarado
Noe alvarado 2012년 4월 12일
댓글: Steven Lord 2022년 2월 7일
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

채택된 답변

Walter Roberson
Walter Roberson 2012년 4월 12일
msize = numel(YourMatrix);
idx = randperm(msize);
If you have a fairly new version of MATLAB, you can instead use
msize = numel(YourMatrix);
YourMatrix(randperm(msize, x))
  댓글 수: 10
Walter Roberson
Walter Roberson 2021년 9월 3일

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

추가 답변(2개)

Prasobhkumar P. P.
Prasobhkumar P. P. 2020년 7월 28일
편집: Walter Roberson 2021년 9월 3일
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 2021년 9월 3일
편집: Adam Wyatt 2021년 9월 3일
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
Steven Lord
Steven Lord 2022년 2월 7일
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.)

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


Find more on Loops and Conditional Statements 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!

Translated by