Generate a random decimal number between 0 and 1

72 views (last 30 days)
Hi guys. Do you know how can I generate a random decimal number between 0 and 1? I tried x=randi(0 1) but this doesn't work for some reason.
Thank you.

Accepted Answer

John D'Errico
John D'Errico on 12 Dec 2020
Edited: John D'Errico on 12 Dec 2020
So why not try rand?
When you have a problem in MATLAB, use tools like help and lookfor to learn how to solve them. For example, you know how to use randi. So read the help for randi.
help randi
...
At the bottom of what you see, you will find this line:
See also rand, randn, randperm, rng, RandStream
The see also line is of huge importance here, because it gives you hints about related functions. Now, look at the help for those tools. You might find the first one suits your purpose EXACTLY.
Next, if you have no idea how to use any tool, including randi, you could also have used lookfor. I just tried
lookfor random
A few lines down there, I found this:
rand - Uniformly distributed pseudorandom numbers.
Hmm. Do you think rand might help you to do this? READ THE HELP FOR RAND. Lookfor can help you to find the tools you need to use.
Finally, if you have no idea how to do any of this, then you REALLY need to read the short courses out there, as this is a really basic question. Try the MATLAB Onramp tutorial. Or look on Youtube, where a quick search turned up at least a few user created tutorials on MATLAB.
It is ok to read the manual.
  2 Comments
George Sfinarolakis
George Sfinarolakis on 12 Dec 2020
First of all thank you very much for the time you spent in my question.
I know rand but this doesn't work either. I guess I have another type of mistake like a typo or something. I'll look it with a clear mind again.
Thanks again for your time.
John D'Errico
John D'Errico on 14 Dec 2020
Never just say that something does not work. Of course it works! You stated only:
"a random decimal number between 0 and 1?"
Did it generate an error when you tried it? If so, then report the error, the COMPLETE text of the error, everything in red. Otherwise, we cannot know what you did, what you tried to do.
Did it do something you are not expecting? Since rand dows exactly what you asked to do, i.e., generate a pseudo-random variate in the interval (0,1), then you need to tell us what you were expecting, and why you think it does not work.
rand()
ans = 0.5347
So if rand does not work for you, then in order for anyone to help you, you need to explain why you think it fails, when it clearly should not fail. (Did you write a function of your own named rand? If so, then this was a bad idea, since MATLAB will now not find rand, but try to use what you wrote.)

Sign in to comment.

More Answers (0)

Categories

Find more on Mathematics 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!