MATLAB: How to draw normal line at given points

normal line

Hello everyone,
I have a red curve that fit 4 bleu points. I want to draw normal at these points.
Here attached my curve.
and the x, y coordinates of the bleu points are :
x=[142;127;181;234];
y=[251;251;261;255];
So, please, how to get the normal line ?
I will be very grateful if anyone could help me.

Best Answer

Try this:
x=[142;127;181;234];
y=[251;251;261;255];
[x, idx] = sort(x);
y = y(idx);
points = [x y];
xint = linspace(127,234,50)';
spl = spline(x,y);
tangent_vector = zeros(4,2);
for i=1:4
if i==4 % last polynomial need to evalauted at endpoint
deri_coef = polyder(spl.coefs(i-1,:));
tangent_vector(i, :) = [1 polyval(deri_coef, x(end)-x(end-1))];
else
deri_coef = polyder(spl.coefs(i,:));
tangent_vector(i, :) = [1 polyval(deri_coef, 0)];
end
end
normal_vec = [-tangent_vector(:,2) tangent_vector(:,1)];
start_points = points;
end_points = 10*normal_vec + points;
fig = figure;
ax = axes();
hold(ax);
t = plot(y,x,'.',ppval(spl,xint),xint,'r-');
for i=1:4
p1 = start_points(i,:);
p2 = end_points(i,:);
plot([p1(2) p2(2)], [p1(1) p2(1)], 'r', 'LineWidth', 2);
end
daspect([1 1 1]);
xlim([180 340])
ylim([100 250])