How to obtain and plot perpedicular lines using the gradient of a function

3 visualizaciones (últimos 30 días)
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.

Respuesta aceptada

Matt J
Matt J el 27 de Sept. de 2022
Editada: Matt J el 27 de Sept. de 2022
Your plot is correct. The lines just don't look perpendicular because of the plot aspect ratio.
x = linspace(-2,1,100)';
y = 5*x.^2 + 3*x - 4 ;
dy = gradient(y, x) ;
%tangency data
x0=0.02;
y0=interp1(x,y,x0);
dy0=interp1(x,dy,x0);
% Obtain tangent: y - y0 = slope*(x - x0)
b0 = y0 - dy0.*x0 ;
ytan = dy0.*x + b0 ;
% Obtain perpendicular
dy0p= -1/dy0 ;
b0p = y0 - dy0p.*x0 ;
yperp = dy0p.*x + b0p ;
% Plot
figure ;
plot(x,[y,ytan,yperp]); legend('y','tangent','perpendicular')
axis equal;
grid on

Más respuestas (0)

Categorías

Más información sobre Graphics en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by