Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- x =[2 4 5 3 9 10]
- y =[-10 8 4 -5 9 10]
- plot(x,y,'*')
- [min_y,i] = min(y);
- pivot = [x(i),y(i)];
- number = i
- %getting the angle
- x(i) = [];
- y(i) = [];
- delta_x = x - ones(1,length(x))*pivot(1);
- delta_y = y - ones(1,length(y))*pivot(2);
- theta = atan2d(delta_y,delta_x);
- %sorting without losing the position
- c = [];
- x_new= [];
- y_new = [];
- for n = 1:length(theta)
- [min_theta, d] = min(theta);
- c = [c d];
- x_new = [x_new x(d)];
- y_new = [y_new y(d)];
- theta(d) = [1000]; %random value need to be higher than 180 degrees
- end
- x_new = [pivot(1) x_new pivot(1) x_new(1)];
- y_new = [pivot(2) y_new pivot(2) y_new(1)];
- %using cross product in this exercise none of the lines are collinear
- %If the result is 0, the points are collinear;
- %if it is positive, the three points constitute a "left turn" or counter-clockwise orientation,
- %otherwise a "right turn" or clockwise orientation (for counter-clockwise numbered points)
- %source wiki
- n_bad = [];
- n_good = [];
- x_new
- y_new
- for n = 1:(length(x_new)-3) %this caused by how the array x_new and y_new contain duplicates
- x_new(n+1)
- cross_product = (x_new(n+1) - x_new(n))*(y_new(n+2)-y_new(n))-((y_new(n+1)-y_new(n))*(x_new(n+2)-x_new(n)))
- if cross_product < 0
- n_bad = [n_bad n+1];
- end
- if cross_product > 0 %this is unnecassaray can be used for skipping making the program faster
- n_good = [n_good n+1]
- end
- end
- %in case I did something wrong the graph can be plotted here:
- figure
- x_good = [pivot(1) x_new(n_good) pivot(1)];
- y_good = [pivot(2) y_new(n_good) pivot(2)];
- plot(x_good,y_good)
- %to get the same index as the input
- if number>1
- n_good = n_good + 1;
- n = sort([n_good number]);
- else
- n = [number n_good];
- end
- n
Add Comment
Please, Sign In to add comment