How do I create a single random number between two values?
显示 更早的评论
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.
1 个评论
Kabeer Akande
2015-9-17
1e3 + (1e9-1e3).*rand(1,1);
采纳的回答
更多回答(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 个评论
Marvin
2012-3-22
Nathan Greco
2012-3-22
rand(100,1) means create a random matrix of size [100x1] of values on the open interval of (0,1).
Image Analyst
2012-3-22
I agree that it might have been confusing since they didn't say what the 100 was right there in the example. You can send an email to support@mathworks.com if you find their documentation confusing. Perhaps they can change the wording to make it more clear. For example, tell them it should say "Generate 100 values from the uniform distribution on the interval [a, b]"
Andrew Sol
2023-3-13
And how to make it so that the minimum and maximum are included in the generated series of numbers?
@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
0 个投票
To generate a random number between [a,b]:
r = a + (b-a)*rand();
To generate N numbers:
r = a + (b-a)*rand(1,N);
类别
在 帮助中心 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!