How can the two source codes be combined into one algorithm?

조회 수: 1 (최근 30일)
cephas mulungi
cephas mulungi 2020년 10월 12일
댓글: Walter Roberson 2020년 10월 25일
Iam trying to combine the follwing two source codes below but Iam finding it hard
kmeans
#Sarwat Shaheen #214677322
clear; clc;
#load dataset twodpoints.txt
D = load('twodpoints.txt');
% N-dimensional output vector assigning each point to its cluster
O = zeros(length(D),1);
%Plotting the initial unclustered data
X1 = D(:,1); X2 = D(:,2);
plot(X1,X2,'r*'); xlabel('X1'); ylabel('X2'); title('Plot of dataset.');
str = {'For this dataset, 3 clusters would be ideal for fitting the data.'};
text(-4.8,18,str,'FontSize',17);
%Choosing the 3 initial centers manually by hand
Mean1 = D(200,:); Mean2 = D(131,:); Mean3 = D(8,:);
%Implementation of the K-means algorithm with 50 iterations for convergence
for i = 1:50
% Creating the three cluster grouping matrices
C1 = zeros(1,2); C2 = zeros(1,2); C3 = zeros(1,2);
% Iterating over all points in the dataset
for j = 1:length(D)
% Calculating the minimum euclidean distance from mean to dataset
%Then assigning each dataset to its particular cluster
dist1 = norm(D(j,:) - Mean1, 2);
dist2 = norm(D(j,:) - Mean2, 2);
dist3 = norm(D(j,:) - Mean3, 2);
if ((dist1 < dist2) && (dist1 < dist3))
O(j,1) = 1;
C1 = [C1; D(j,:)];
elseif ((dist2 < dist1) && (dist2 < dist3))
O(j,1) = 2;
C2 = [C2; D(j,:)];
else
O(j,1) = 3;
C3 = [C3; D(j,:)];
endif
endfor
% Updating the centers of each cluster
Mean1(1,1) = sum(C1(:,1)) / (length(C1) - 1); Mean1(1,2) = sum(C1(:,2)) / (length(C1) - 1);
Mean2(1,1) = sum(C2(:,1)) / (length(C2) - 1); Mean2(1,2) = sum(C2(:,2)) / (length(C2) - 1);
Mean3(1,1) = sum(C3(:,1)) / (length(C3) - 1); Mean3(1,2) = sum(C3(:,2)) / (length(C3) - 1);
endfor
% Final N-dimensional vector outptut
disp(O);
%Plot of data after k-means clustering, with different color for each cluster
scatter(C1(:,1),C1(:,2)); hold on;
scatter(C2(:,1),C2(:,2));
scatter(C3(:,1),C3(:,2));
xlabel('X1'); ylabel('X2'); title('Plot of dataset after k-means clustering.');
text(D(200,1),D(200,2),'\leftarrowInitial center-1.','FontSize',15);
text(D(131,1),D(131,2),'Initial center-2\rightarrow','HorizontalAlignment','right','FontSize',15);
text(D(8,1),D(8,2),'\leftarrowInitial center-3.','FontSize',15);
text(Mean1(1,1),Mean1(1,2),'x\leftarrowFinal center-1.','Color', 'red','FontSize',13);
text(Mean2(1,1),Mean2(1,2),'x\leftarrowFinal center-2.','Color', 'red','FontSize',15);
text(Mean3(1,1),Mean3(1,2),'x\leftarrowFinal center-3.','Color', 'red','FontSize',15);
text(-10,18,'Second instance of manually chosen initial centers,C1 = twodpoints[200],C2 = twodpoints[131],C3 = twodpoints[8].','FontSize',10);
t = linspace(0,2*pi,100)';
c1x = 3.2.*cos(t) + Mean1(1,1); c1y = 3.3.*sin(t) + Mean1(1,2); plot(c1x,c1y); text(3.3,-1.6,'Cluster 1','FontSize',15);
c2x = 5.*cos(t) + Mean2(1,1); c2y = 4.*sin(t) + Mean2(1,2); plot(c2x,c2y); text(-7,15,'Cluster 3','FontSize',15);
c3x = 5.*cos(t) + Mean3(1,1); c3y = 4.*sin(t) + Mean3(1,2); plot(c3x,c3y); text(10.1,13,'Cluster 2','FontSize',15);
Distance Algortihm
clc
close all
clear all
Elec=50*0.000000001;
Emp=100*0.000000000001;
k = 8;
Area = input('Enter Network Area:- ');
Nodes=input('Enter Number of nodes:-');
Points=[];
figure(1),axis([0,Area,0,Area])
for k1=1:Nodes
[x y]=ginput(1);
hold on
plot(x,y,'*','linewidth',4)
text(x+1,y+1,num2str(k1))
Points=[Points,[x y]];
%disp({'Coordinates For Node ' num2str(k1) ' ^re: '})
disp(num2str([x y]))
end
input('Press Any key to give coordinates of Bstation')
hold on
[x y]=ginput(1);
hold on
plot(x,y,'Bs','linewidth',10)
text(x+1,y+1,'Bs')
Bstation=[x y];
disp({'Coordinates For Base Station Are: '})
disp(num2str([x y]))
figure(2),plot(Points(:,1),Points(:,2),'*r','linewidth',2);
axis([0 Area 0 Area])
hold on
plot(Bstation(1,1),Bstation(1,2),'sb','linewidth',5)
text(Bstation(1,2)+1,Bstation(1,2)+'Base station')
% Total Nodes
no=size(Points,1);
for jk=1:no
text(Points(jk,1)+2,Points(jk,2)+2,{'N'Num3str(jk)})
end
% Distance Calculation
X1=Points(x1,1);
Y1=Points(x1,2);
for x2=1:no
X2=Points(x2,1);
Y2=Points(x2,2);
Euc_dist=sqrt((X1-X2)^2+(Y1-Y2)^2);
Euc_dist=ceil(Euc_dist);
Final_dist(x1,x2)=Euc_dist;
end
end
Simdst=sum(Final_dist);
disp('Distance Matrix Is:= ')
disp(Final_dist)
disp('Simulation of Distances of Each Node: ')
disp(SimDist)
%Base Station Distance
for nm=1:Nodes
X1=Points(nm,1);
Y1=Points(nm,2);
X2=Bstation(1,1);
Y2=Bstation(1,2);
Edist=sqrt((X1-X2)^2+(Y1-Y2)^2);
Edist=ceil(Edist);
Bsdist(1,nm)=Edist;
end
[Simdst Nodenmbr]main(Bsdist)
disp('Net Distance from Base Station: ')
disp(Bsdist)
disp(['The Node' num2str(Nodenmbr) 'Is Selected As a Cluster Head'])
disp(['With Distance: ' num2str(SimBsdist)])
disp('Distance Based on Cluster Head Selection')
disp(Final_Dist(i.nodembr)')
%CH Based Energy Calculation
Nodedst=(Final_dist(:,Nodembr)');
loop=length(Nodedst);
for i=1:loop
d=Nodedst(1,i);
if d==0
d=1;
end
Energydsp(1,i)=(Elec*K)*(Emp*K*d*d);
end
format short g
Energydsp=Energydsp*1000000000;
disp('Cluster Head Based Energy of Each Node: ')
disp(num2str(Energydsp))
% Non CH energy Calculation
NonChdist=abs(Bsdist-SimDist);
loop2=length(NonChdist);
for i=1:loop2
d=NonChdist(1,i);
NCHEnergy(1,i)=(Eelec*K)+(Emp*8*d*d);
end
NCHEnergy=NCHEnergy*1000000000;
disp('Non Cluster Head Based of Each Node: ')
disp(num2str(NCHEnergy))
figure(3),bar(Nodedst),title('Energy Graph')
xlabel('Nodes Number')
ylabel('Energy')
figure(4),bar(NonChdist),title('Distance Graph of ClusterHead')
xlabel('Nodes Number')
ylabel('Distance')
figure(4),bar(Nondist),title('Distance Graph of ClusterHead')
xlabel('Nodes Number')
ylabel('Distance')
  댓글 수: 2
John D'Errico
John D'Errico 2020년 10월 25일
learn to use functions.
Walter Roberson
Walter Roberson 2020년 10월 25일
Yep, functions are natural for this purpose.
If you have a well defined non-trivial piece of work to do, and another routine that needs that kind of work done, putting the well-defined work into a function typically makes it much easier to debug the overall code -- and you get to re-use the function for other purposes, saving you from having to re-create and debug the code in that newer situation.
About the only time you should consider deliberately merging non-trivial code together with larger code, is if the function call overhead is adding up significantly for a function that is being called a lot (that is, that the microseconds you might save could add up to weeks of months over the lifetime of the program.) But function call overhead is typically small compared to the work done inside a function, except that checking the validity of arguements can indeed add up substantially. About the only exception, the only code pattern where it makes sense to "inline" a function, is if the function spends most of its time deciding what to do based upon constant parameters passed in -- in that case, when you "inline" the code, an optimizer might be able to remove most of the code body by pruning down to just the branch corresponding to what the constant parameters would be.

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Particle & Nuclear Physics에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by