How do I create a single random number between two values?
조회 수: 97 (최근 30일)
이전 댓글 표시
I need to create a value for one of my variables in a loop which will run ten times. I need it to be between two set values, e.g. 1e3 and 9e3. Sorry for what is probably a very basic question but I am new to matlab.
채택된 답변
Wayne King
2012년 3월 22일
Does it have to be an integer, or any number between 1e3 and 9e3?
For the former:
Int = randi([1e3 9e3],1,1);
For the latter:
R = 1e3+8e3*rand(1,1);
The preceding line gives you a uniform random number between 1e3 and 9e3.
댓글 수: 4
추가 답변 (3개)
Image Analyst
2012년 3월 22일
The help facility is always a good place to start. If you had searched the help for rand, you would have seen the very first example:
Example 1
Generate values from the uniform distribution on the interval [a, b]:
r = a + (b-a).*rand(100,1);
댓글 수: 6
Image Analyst
2023년 3월 13일
@Andrew Sol Since they will not be there (infinitesimally small chance) if you're just getting random numbers, you will have to add them in manually: Somthing like:
% Generate values from the uniform distribution on the interval [a, b]:
a = 5;
b = 10;
numElements = 7;
r = a + (b-a).*rand(numElements,1);
% Add in the max and min
r = [a; b; r];
% Scramble the array so they are not at the beginning
scrambledIndexes = randperm(numel(r));
r = r(scrambledIndexes)
Andrew Sol
2023년 3월 13일
@Image Analyst Thank you very much for your answer! it's really not that complicated
Nisha Bharti
2022년 1월 12일
To generate a random number between [a,b]:
r = a + (b-a)*rand();
To generate N numbers:
r = a + (b-a)*rand(1,N);
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!