Search code examples
matlabrandomplotsynthetic

How to generate random two concentric spheres synthetic data?


How to generate random two concentric spheres synthetic data with radius1=40 and radius2 =100 in MATLAB and save that data in format *.mat with one variable.(1000*3 double)? Also, how to plot this data in 3D with 2 colors: red and blue?

My Code:

rng(0,'twister');
rvals = 2*rand(1000,1)-1;
elevation = asin(rvals);

azimuth = 2*pi*rand(1000,1);

radii = 3*(rand(1000,1).^(1/3));

[x,y,z] = sph2cart(azimuth,elevation,radii);
data=[x,y,z];
figure
plot3(x,y,z,'.');
axis equal

Expected Output:

enter image description here


Solution

  • If you want a fixed radius then assign them a constant value (instead of a random value) and keep the random numbers for the orientation angles (azimuth/elevation or theta/phi depending on notation).

    This code:

    rng(0,'twister');
    nptSet = 500 ; r1 = 40 ; r2 = 100 ;                 %// your constraints
    
    %// first data set (r1=40)
    r1    = zeros(nptSet,1)+r1  ;           %// assign radius (fixed)
    azi1  = rand( size(r1) ) * 2*pi ;       %// random azimuth   [  0     2pi]
    elev1 = (rand(size(r1)) .* pi)-pi/2 ;   %// random elevation [-pi/2  pi/2]
    
    %// second data set (r2=100)
    r2    = zeros(nptSet,1)+r2  ;           %// assign radius (fixed)
    azi2  = rand( size(r2) ) * 2*pi ;       %// random azimuth   [  0     2pi]
    elev2 = (rand(size(r2)) .* pi)-pi/2 ;   %// random elevation [-pi/2  pi/2]
    
    %// convert to cartesian
    [x1,y1,z1] = sph2cart(azi1,elev1,r1);
    [x2,y2,z2] = sph2cart(azi2,elev2,r2);
    
    %// display and refine
    figure ; hold on
    plot3(x1,y1,z1,'or','MarkerSize',2);
    plot3(x2,y2,z2,'+b');
    xlabel('x') ; ylabel('y') ; zlabel('z')
    axis equal ; grid off ; view(50,30)
    

    Will get you that figure: spheredots