Search code examples
pythonmatlab3dfigurehelix

How to generate 3D helix in MATLAB or Python?


I have written a code to generate x, y, z points of a helix and got this result:

What I got

Code:

clear all; delete all, clc;
% Spiral constants
THETA_0 = 5; % constant
THETA_1 = 10.3; % starting angle
A = 3.762;
B = 0.001317;
C = 7.967;
D = 0.1287;
E = 0.003056;

s=2;
% Calculate (x,y,z) coordinates of points defining the spiral path
theta = THETA_1:.1:910.3;  % range, starting degree angle:final degree angle
for i = 1:length(theta)
    if (theta(i)<=99.9)
        R(i) = C*(1-D*log(theta(i)-THETA_0));
    else
%       theta_mod = 0.0002*theta(i)^2+.98*theta(i);
        R(i) = A*exp(-B*theta(i));
    end
    % scaling 
    x(i) = s*R(i)*cosd(theta(i));
    y(i) = s*R(i)*sind(theta(i));
    z(i) = s*E*(theta(i)-THETA_1);
end

helix=animatedline('LineWidth',2);
axis equal;
axis vis3d;
% set (gca,'XLim', [-5 5],'YLim', [-10 10], 'ZLim',[0 6])
view(43,24);
hold on;
for i=1:length(z)
    addpoints(helix, x(i),y(i),z(i));
    head=scatter3 (x(i),y(i),z(i));
    drawnow
%   pause(0.01);
    delete(head);
end

and I want a helical structure around it similar to this

Intended 3D


Solution

  • Your second picture give you:

    • The parametric equations for x,y and z.
    • The restriction on u and v

    You have all the necessary informations to create your geometry:

    %plot the mesh
    u=linspace(0,4*pi,50);
    v=linspace(0,2*pi,50);
    [u,v]=meshgrid(u,v);
    x=(1.2+0.5*cos(v)).*cos(u);
    y=(1.2+0.5*cos(v)).*sin(u);
    z=0.5*sin(v)+u/pi;
    surf(x,y,z)
    hold on
    
    %plot the 3d line
    u = linspace(0,4*pi,40)
    x=1.2.*cos(u);
    y=1.2.*sin(u);
    z=u/pi;
    plot3(x,y,z,'r');
    
    axis equal
    

    Now you just have to adjust the parametric equations to fit your line.

    enter image description here

    EDIT: To apply the same solution to your specific case you simply have to replace u and v with your theta and R variable in the meshgrid function:

    THETA_0 = 5; % constant
    THETA_1 = 10.3; % starting angle
    A = 3.762;
    B = 0.001317;
    C = 7.967;
    D = 0.1287;
    E = 0.003056;
    
    s=2;
    % Calculate (x,y,z) coordinates of points defining the spiral path
    theta = THETA_1:5:910.3;
    for i = 1:length(theta)
        if (theta(i)<=99.9)
            R(i) = s*C*(1-D*log(theta(i)-THETA_0));
        else
            R(i) = s*A*exp(-B*theta(i));
        end
    
    end
    
    x = R.*cosd(theta);
    y = R.*sind(theta);
    z = E.*(theta-THETA_1);
    plot3(x,y,z,'r','linewidth',2)
    
    hold on
    [u,v]=meshgrid(theta,R);
    x=(R+0.5*cos(v)).*cosd(u);
    y=(R+0.5*cos(v)).*sind(u);
    z=0.5*sin(v)+E.*(u-THETA_1);
    mesh(x,y,z,'facecolor','none')
    
    axis equal
    

    Result:

    enter image description here

    by the way I'm not a big fan of mixing cosd and cos in the same script, but do what you want.