Calculate perpendicular line to an 3rd order polynomial

2 views (last 30 days)
Adam
Adam on 24 May 2021
Edited: darova on 25 May 2021
Hi all,
I have been trying to calculate the perpendicular line to an 3rd order (or higher) polynomial line.
I found a way to do it with an 2nd order polynomial, however, can't work out how to do it for any higher.
This calcualtion would make my data analysis a lot quicker, but is not essential. I've tried a bunch of stuff and I think this is my last hope.
Thanks in advance for any help.

Accepted Answer

Torsten
Torsten on 24 May 2021
For a general function f, the formula for the perpendicular line to the function through (x0,f(x0)) is
y = f(x0) + (x-x0)* ( -1/f'(x0) )
  1 Comment
Adam
Adam on 25 May 2021
Thanks mate.
Helped me figure it out.
For people looking for something similar I have written this basic script that should help.
It could probably be done better and more efficient, but I am a bit of a Matlab rookie.
Hopefully this is a good start for anyone looking. See below.
pow = 4; % power of the poly can be between 3 and 5.
% It could be more, but it is constrained by the if function in the script.
x = linspace(0,1,5);
y = 1./(1+x);
scatter(x,y);
p = polyfit(x,y,pow);
hold on
yy = polyval(p,x);
plot(x,yy)
k2 = polyder(p);
if pow==3
y2 = k2(1)*x.^2 + k2(2)*x + k2(3);
elseif pow==4
y2 = k2(1)*x.^3 + k2(2)*x.^2 + k2(3)*x + k2(4);
elseif pow==5
y2 = k2(1)*x.^4 + k2(2)*x.^3 + k2(3)*x.^2 + k2(4)*x + k2(5);
end
for i = 2:4
y3 = y2(i);
pe = -1/y3;
X1 = x(i);
Y1 = y(i);
X2 = X1+.2;
Y2 = pe*(X2 - X1)+Y1;
plot([X2, X1], [Y2, Y1],':','LineWidth', 2);
X3 = X1-.2;
Y3 = pe*(X3 - X1)+Y1;
plot([X3, X1], [Y3, Y1],'--', 'LineWidth', 2);
end
axis equal

Sign in to comment.

More Answers (0)

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!