📄 minimumdistance.m
字号:
function mindist = minimumdistance(X,Y,x,y)
% Function to find the minimum distance loop from given set of points.
% This function uses the distance formula to genrate a minimum distance
% loop.
% X = X coordinate vector
% Y = Y coordinate vector
% (x,y) point where the loop is to be started
% This point is labeled as 1 and then the rest in (X,Y) starting from 2
% onwards
% mindist = final value of the minimum distance from point (x,y) to (x,y)
[ans,pathname]=uigetfile( ...
{'*.jpg';'*.jpeg'...
}, ...
'Select an IMAGE');
I=imread([pathname ans]);
image(I)
[X,Y]=ginput(2)
%c=hypot(x,y)
X = [x,X];
Y = [y,Y];
%Plot the X&Y Coordinates
num = length(X);
subplot(1,2,1); plot(X,Y,'.');
axis([0 max(X)+2 0 max(Y)+2]);
hold on
plot(x,y,'s','MarkerEdgeColor','k','MarkerFaceColor','g','MarkerSize',10);
%Matrix for the distances between each and every point.
%for i==j, distance between a point and itself is given the value inf.
dist = inf(num,num);
for i=1:1:num
for j=1:1:num
if i~=j
dist(i,j) = sqrt((X(i)-X(j))^2 + (Y(i)-Y(j))^2);
end
end
end
%Saving the dist matrix for later use
dist1 = dist;
%plotting the loop
%Starting point is origin.
I=1;
J = zeros(1,num);
W = zeros(1,num);
mindist = 0;
for j=1:1:num
%Find the closest point to the point 1 (origin)
%If 2 points have same distance from a point the first point will be
%chosen by default. eg. 1,3 & 1,5 are equidistant from a point;
%1,3 is chosen.
J(j)=I;
[C,I] = min(dist(I,:));
if j<num
mindist = mindist + C;
end
%Once a point is used, mark all the distances from it as Inf to avoid
%reusing that point again
dist(J(j),:) = inf;
dist(:,J(j)) = inf;
%Weight Matrix, points in order of their distances
W(j) = J(j);
end
%Add the distance from the last point to the first point.
mindist = mindist + dist1(W(num),1);
%X and Y coordinates w.r.t the weight matrix
Xnew = zeros(1,num);
Ynew = zeros(1,num);
per = 0.001*num;
for j=1:1:num
Xnew(j) = X(W(j));
Ynew(j) = Y(W(j));
text(X(j)-(per),Y(j)-(per),num2str(j));
end
%Plot the resulting loop
Xnew = [Xnew,X(1)];
Ynew = [Ynew,Y(1)];
subplot(1,2,2)
plot(X,Y,'.');hold on
plot(Xnew,Ynew,'-rs');
plot(x,y,'s','MarkerEdgeColor','k','MarkerFaceColor','g','MarkerSize',10);
axis([0 max(X)+2 0 max(Y)+2]);
%Label the resulting loop
for j=1:1:num
text(X(j)-(per),Y(j)-(per),num2str(j));
end
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -