how can I generate a random angle?

66 ビュー (過去 30 日間)
Rad Bazargan
Rad Bazargan 2019 年 4 月 11 日
コメント済み: Jon 2019 年 4 月 11 日
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.

採用された回答

Star Strider
Star Strider 2019 年 4 月 11 日
Try one of these:
rangrad = 2*pi*rand; % Radians
rangdeg = 360*rand; % Degrees
Experiment to get the result you want.
  3 件のコメント
Star Strider
Star Strider 2019 年 4 月 11 日
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 2019 年 4 月 11 日
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.

サインインしてコメントする。

その他の回答 (1 件)

Jon
Jon 2019 年 4 月 11 日
編集済み: Jon 2019 年 4 月 11 日
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);

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by