clc;
clear all;
close all;
Distance = [0,2,4,6,6,8;
2,0,4,6,6,8;
4,4,0,6,6,8;
6,6,6,0,4,8;
6,6,6,4,0,8;
8,8,8,8,8,0];
S = ['A','B','C','D','E','F'];
L = length(Distance(:,1));
r= [];
SResult = [];
STemp = [];
%% NJ Algorithm
while L > 2
%calculate r(i)=sum(d(i,k))/(L-2);
r = [];
for i = 1:L
r = [r;sum(Distance(:,i))/(L-2)];
end
%calculate D(i)= d(i,j) - r(i) -r(j);
for i =1:L
for j =1:L
if i == j
DistanceTemp(i,j) = 0;
else
DistanceTemp(i,j) = Distance(i,j) - r(i) - r(j);
end
end
end
%find min weight
minWeight = min(min(DistanceTemp));
[row,con] = find(DistanceTemp == minWeight);
row = row(1);
con = con(1);
STemp = strcat(S(min(row,con)),S(max(row,con)));
SResult = [SResult,STemp]
S(row) = [];
S(con) = [];
S = strcat(S,STemp);
%update Distance
CombineVector = (Distance(row,[1:min(row,con)-1,min(row,con)+1:max(row,con)-1,...
max(row,con)+1:L]) + Distance(con,[1:min(row,con)-1,min(row,con)+1:max(row,con)-1,...
max(row,con)+1:L]) - Distance(row,con))/2;
Distance = Distance([1:min(row,con)-1,min(row,con)+1:max(row,con)-1,...
max(row,con)+1:L],[1:min(row,con)-1,min(row,con)+1:max(row,con)-1,...
max(row,con)+1:L]);
L = length(Distance(:,1));
Distance(L+1,1:L) = CombineVector;
Distance(1:L,L+1) = CombineVector';
Distance(L+1,L+1) = 0;
L = L + 1;
end