Search code examples
matlabmatlab-figurecurve

How to draw tangent line at specified points in a curve in Matlab


I am having a an array of points x,y and respective angles at those specified points. I want to plot a tangent line at those points, i am unable to figure out how to proceed.

http://postimg.org/image/s2y1pqqaj/

As shown in command window 1st column contains x points , 2nd column contains y points and 3rd column the respective tangent angle. Figure 1 is plot between x and y points. I know the slope i.e tangent angle at every point as you can see it in the 3rd column. But not able to understand how to implement it to draw tangent at these points . Also the equation for tangent line 'y = mx + b' where m - slope and b is y intercept. Thanking you.

Here is the code

% Fill in parr a list of points and tangents to be used for display.
% @param parr (x,y) Array of points.
% @param tan Array of tangents.
% @param lengthStep Distance between points.

 function [x y tan] = GetPointListForDisplay(m_Length,r1,r2,count)

   global nn ca ce length; 

   GetLength = m_Length;
   length = GetLength;   

   ca = GetCurvatureAtDeltaLength(0.0);     
   ce = GetCurvatureAtDeltaLength(length);

   %if ((abs(ca) < 1.0/10000.0) && (abs(ce) < 1.0/10000.0))
   %end

   radius = 1.0 ./ max(abs(ca), abs(ce));

   %if (radius < 0.1)
   %end

   nn = 3 + (180.0 * length/(2*pi*radius));  % Using modified formula of arc here

   lengthStep = length/nn; 
   currLen = -lengthStep;

   while (1) 

       currLen = currLen + lengthStep;
       if (currLen > m_Length)

           currLen = m_Length; 
       end

       [x,y] = GetPointAtDeltaLength(currLen);
       [tan] = GetTangentGridBearingAtDeltaLength(currLen); 

       z(count,1) = x;
       z(count,2)= y;
       z(count,3)= tan;

       figure(1);

       %plot(z(count,1).*sin(z(count,3)),z(count,2).*cos(z(count,3)),'b*');
       %plot(z(1,count).*cos(z(3,count)),z(2,count).*sin(z(3,count)),'b*');
       plot(z(count,1),z(count,2),'b*');
       %plot(z(1,count),z(2,count),'b*');
       hold on;

       %pause(0.1);

       count=count+1;
       axis equal;     

       if (currLen >= m_Length)
          z(count,1)= tan
          break;
       end

   end

 end 

Regards,

Mrinal


Solution

  • ii = index of the point where you want to get the tangent
    x1 = left bound of your tangent
    x2 = right bound of your tangent
    xT = z(ii,1)  %argument where you want to get the tangent
    yT = z(ii,2)  %corresponding y
    mT = tan(z(ii,3))   % corresponding slope
    

    I assume you just want one tangent, then plot it like this.

    plot( [x1,xT,x2] , [yT-mT*(xT-x1), yT, yT+mT*(x2-xT)] )
    

    Otherwise just use a loop for more tangents using ii as iteration variable.

    The string for your equation would be

    eq = strcat('y = ',num2str(mT),'*x + ',num2str(yT-mT*xT))