how can I generate a random angle?

32 views (last 30 days)
Rad Bazargan
Rad Bazargan on 11 Apr 2019
Answered: yerram on 8 Jul 2024
I want to plot a random straight line with a fixed length based on the coordinates of a random point. Therefore I need to find a random angle. I figured everything out but the angle.

Accepted Answer

Star Strider
Star Strider on 11 Apr 2019
Try one of these:
rangrad = 2*pi*rand; % Radians
rangdeg = 360*rand; % Degrees
Experiment to get the result you want.
  3 Comments
Star Strider
Star Strider on 11 Apr 2019
I don¹t understand what you mean by ‘earlier answer’. Was it to another question?
My Answer posted first here to this one.
Jon
Jon on 11 Apr 2019
Sorry, I guess we must have sent the answers in at almost the same time and they collided. I hadn't noticed yours until I came back later, and so I mistakenly thought it was a later post.

Sign in to comment.

More Answers (2)

Jon
Jon on 11 Apr 2019
Edited: Jon on 11 Apr 2019
Use randn or rand depending upon whether you want the angles to be normally distributed or uniformly distributed.
Since randn produces values with a mean of zero and a standard deviation of 1, you must scale it to get values that are in the range of 0 to 2*pi, and since the values may in fact be larger in magnitude than that you can keep them in the range [0,2*pi] by using the mod function. Note that the result will be random, but due to the mapping to the range [0,2*pi] they will not be normally distributed
Here is some example code that would produce N random angles using randn
N = 100; % number of random angles to generate
% compute normally distributed values with zero mean and standard deviation of 2*pi
thetaNormal = 2*pi*randn(N,1);
% map them to the range [0,2*pi]
theta = mod(thetaNormal,2*pi)
Alternatively, if the uniform distribution is OK for your purposes you can do this more simply
N = 100; % number of random angles to generate
% compute uniformly distributed values ranging from 0 to 1 and scale them to range 0 to 2*pi
theta = 2*pi*rand(N,1);

yerram
yerram on 8 Jul 2024
i want to generate random phase for two sine signal but i dont know how to do it can you help with that code

Community Treasure Hunt

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

Start Hunting!