How to obtain and plot perpedicular lines using the gradient of a function
Show older comments
Hi all,
I have a simple function (quadratic in this case) where I would like to plot the lines perpedicular to its tangent for every point. As a first step I define the function and take the gardient to draw the tangent:
clear ; clc
x = (0:100)' ;
y1 = 5*x.^2 + 3*x - 4 ;
% Obtain tangent: y - y1 = slope*(x - x1)
dy1 = gradient(y1, x) ;
b1 = y1 - dy1.*x ;
y1tan = dy1'.*x + b1' ;
% Plot tangent at 50th point to demonstrate
figure ; plot(x, [y1 y1tan(:,50)]) ; legend('y1', 'tangent') ; grid on
The above works perfectly, so I proceed to use the similar method to obtain the perpendicular line to the tangent I just drew:
% Obtain perpendicular
dy1p= -1./dy1 ;
b1p = y1 - dy1p.*x ;
y1perp = dy1p'.*x + b1p' ;
% Plot
figure ; plot(x, [y1 y1tan(:,50) y1perp(:,50)]) ; legend('y1', 'tangent', 'perpendicular') ; grid on
As you can see, for some reason I am unable to get the perpendicular line which I do not understand why. Similar posts in the past that I have looked, don't seem to be doing anything radically different so I am struggling to understand why I can't accomplish this.
Thanks for your help in advance.
Accepted Answer
More Answers (0)
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

