怎么用Matlab计算很多散点之间最短距离
这样:
clear;
clc;
x=rand(7,1);
y=rand(7,1);
dist=@(var) sum(sqrt((var(1)-x).^2+(var(2)-y).^2));%var(1)=x;var(2)=y
var0=rand(2,1);
[var,minDistance,exitflag]=fminunc(dist,var0)
plot(x,y,'o','markerfacecolor','r','markersize',6);
hold on;
plot(var(1),var(2),'p','markerfacecolor','g')
for i=1:7
plot([var(1),x(i)],[var(2),y(i)],':');
end
扩展资料:
注意事项
先构造一个n(各点的数量)维矩阵,如果是无向图则是对称矩阵:
a(1,2)=2;a(1,3)=8;a(1,4)=1;
a(2,3)=1;a(2,3)=6;a(2,5)=1;
a(3,4)=7;a(3,5)=5;a(3,6)=1;a(3,7)=2;
a(4,7)=9;
a(5,6)=3;a(5,8)=2;a(5,9)=9;
a(6,7)=4;a(6,9)=6;
a(7,9)=3;a(7,10)=1;
a(8,9)=7;a(8,11)=9;
a(9,10)=1;a(9,11)=2;
a(10,11)=4;
找到矩阵中的每一个非零元:
[i,j,v]=find(a);
利用最短距离函数求解:
[x,y,z]=graphshortestpath(b,1,11,'Directed',false) % Directed是标志图为有向或无向的属性,该图是无向图,对应的属性值为false,或0