필터 지우기
필터 지우기

How can use randi function for a specific array of numbers?

조회 수: 13 (최근 30일)
Gavin Thompson
Gavin Thompson 2021년 9월 7일
편집: Dave B 2021년 9월 7일
function selectedValues = selectRandom( dataSet, numberSelected )
% selectRandom: Return numSel elements of input array data selected at
% random. Duplicate selections are acceptable.
% Inputs: data - array of input data values
% numSel - number of randomly selected elements to return
%
% Outputs: selected - array of randomly selected data values
% Choose randomly selected elements for output.
selectedValues = randi(max(dataSet),min(dataSet),numberSelected)
end
selectRandom([ 74, 13, 1, 51, 6 ], 3)
Hello, I am trying to generate a row of 3 random integers located within the array above. How can I tell my code to only pull numbers from the data set instead of all numbers in between?
I also tried this but it doesn't run correctly because it only recognizes scalar values.
randi(dataSet(1:end),1,numberSelected)

채택된 답변

Dave B
Dave B 2021년 9월 7일
편집: Dave B 2021년 9월 7일
How about using randi to pick indices into dataSet?
Alternatively, if you're not constrained to use randi, just use randsample instead (the randsample(population, k) syntax looks very much like your selectRandom syntax)..
selectRandom([ 74, 13, 1, 51, 6 ], 3)
ans = 1×3
6 51 6
selectRandom([ 74, 13, 1, 51, 6 ], 4)
ans = 1×4
6 74 1 13
function selectedValues = selectRandom( dataSet, numberSelected )
selectedValues = dataSet(randi(numel(dataSet), 1, numberSelected));
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Random Number Generation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by