www.gusucode.com > matlab 案例源码 matlab代码程序 > matlab/RandomNumbersWithinASphereExample.m
%% Random Numbers Within a Sphere % %% Section 1 % One way to create points inside a sphere is to specify them in spherical % coordinates. Then you can convert them to Cartesian coordinates to plot % them. %% % First, initialize the random number generator to make the results in this % example repeatable. % Copyright 2015 The MathWorks, Inc. rng(0,'twister') %% % Calculate an elevation angle for each point in the sphere. These values % are in the open interval, $(-\pi/2,\pi/2)$, but are not uniformly % distributed. rvals = 2*rand(1000,1)-1; elevation = asin(rvals); %% % Create an azimuth angle for each point in the sphere. These values are % uniformly distributed in the open interval, $(0,2\pi)$. azimuth = 2*pi*rand(1000,1); %% % Create a radius value for each point in the sphere. These values are in % the open interval, $(0,3)$, but are not uniformly distributed. radii = 3*(rand(1000,1).^(1/3)); %% % Convert to Cartesian coordinates and plot the result. [x,y,z] = sph2cart(azimuth,elevation,radii); figure plot3(x,y,z,'.') axis equal %% % If you want to place random numbers _on the surface_ % of the sphere, then specify a constant radius value to be the last input % argument to |sph2cart|. In this case, the value is % |3|. [x,y,z] = sph2cart(azimuth,elevation,3);