How to set upper and lower limit of random number

조회 수: 67 (최근 30일)
Stephen john
Stephen john 2022년 3월 16일
댓글: Walter Roberson 2022년 3월 17일
Hello everyone, I hope you are doing well. i have the following code. it generate a random number
I want to set the upper limit and lower limit for the values and generate a pattern.
for example i have value 350, then the lower limit will be 300 and upper limit will be 350, or any variable which define the upper and lower limit of the dataset., I have tried the following method but it does not work
levels=round(rand*498)+2;
Dataset=round(rand(1,1000)*(levels*1.1))+round(levels*0.5);
scatter(1:length(Dataset),Dataset)

답변 (2개)

Voss
Voss 2022년 3월 16일
lower_limit = 300; % to use your example values
upper_limit = 350;
% generate a uniformly distributed random *number* between lower_limit and
% upper_limit:
X = rand()*(upper_limit-lower_limit)+lower_limit
% generate a uniformly distributed pseudorandom *integer* between lower_limit
% and upper_limit:
X = randi(upper_limit-lower_limit+1)+lower_limit-1
  댓글 수: 10
Stephen john
Stephen john 2022년 3월 17일
@Walter Roberson not working getting error
Walter Roberson
Walter Roberson 2022년 3월 17일
control = randi([2 1000], 1, 1000);
filtered = nan(size(control));
idx = find(control == 300);
if ~isempty(idx)
%talking about what happens when 300 is first found, is only meaningful
%if 300 was found at all
filtered(idx(1)) = randi([250 300], 1, 1); %250 to 300 the first time
idx = idx(2:end); %remaining locations
end
sometimes = rand(size(idx)) <= .3; %sometimes means a 30% chance, right?
filtered(idx(sometimes)) = randi([250 350], 1, nnz(sometimes));
idx = find(control == 500);
sometimes = rand(size(idx)) <= 0.64; %sometimes means a 64% chance, right?
filtered(idx(sometimes)) = randi([450 550], 1, nnz(sometimes));
%now verify
idx = find(~isnan(filtered))
idx = 1×3
301 707 877
control(idx)
ans = 1×3
500 300 500
filtered(idx)
ans = 1×3
545 294 507

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


David Hill
David Hill 2022년 3월 16일
dataSet=50*rand(1,1000)+300;
  댓글 수: 8
Stephen john
Stephen john 2022년 3월 17일
@David Hill the numbers are generated between 1-1000, then the upper and lower limit of the numbers depend on the span.
David Hill
David Hill 2022년 3월 17일
r=998*rand(1,1000)+2;
span=100;
for k=1:1000
R(k,:)=span*rand(1,50)+r(k)-50;%each row is 50 samples within the +-50 of each element in r
end

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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by