MATLAB Answers

0

How do I use randn vs randi vs rand?

Asked by Tina Huynh on 6 Mar 2017
Latest activity Answered by Walter Roberson
on 12 Oct 2019
I want a 3x5 matrix of random integers between 5 and 10. So I typed the following:
randi ([5,10], 3, 5) and this worked perfectly fine.
When I wanted a 3x5 matrix of random real numbers between 5 and 10, I assumed I would use randn and type:
randn ([5,10], 3,5) but it kept coming up as an error.
Can someone explain to me what I'm doing wrong? I'm just learning how to use MatLab.

  1 Comment

"Can someone explain to me what I'm doing wrong?"
The best place to learn how to use MATLAB is by reading the documentation. And when you read the documentation then you will learn that each of those functions has different syntaxes. For example, the randn documentation clearly states that it generates numbers distributed with the standard normal distribution. It does not mention anywhere that limits for those numbers can be specified (and this would would contradict the definition of the standard normal distribution anyway).
Summary: different functions have different help pages showing different syntaxes using different inputs to give different outputs. Always read the documentation.

Sign in to comment.

2 Answers

Answer by Jan
on 7 Mar 2017
Edited by Jan
on 7 Mar 2017

Reading the documentation should be the first step:
doc rand
doc randn
Whenever you get an error and post a corresponding question in the forum, insert a copy of the complete error message.

  0 Comments

Sign in to comment.


Answer by Walter Roberson
on 12 Oct 2019

rand() : creates uniform random numbers ("with replacement") in the range (0,1) exclusive. To create uniform random numbers in the range (a,b) exclusive, use rand()*(b-a)+a . The only arguments for rand() are the sizes of the resulting array.
randn(): creates random number on the normal distribution ("with replacement") with mean 0 and standard deviation 0. The create normally distributed random numbers with mean a and standard deviation b, use randn()*b + a . The only arguments for randn() are the sizes of the resulting array.
randi(): creates uniform distributed random integers ("with replacement") in a range. If the first argument is a scalar, the range is 1 to that scalar. If the first argument is a vector of length 2, then the range is from the first integer to the second integer. The arguments after the first one are the sizes of the resulting array.
If you need uniform random integers without replacement on the range [a b] then use randperm(b-a+1)+a-1

  0 Comments

Sign in to comment.