How can I write the first function as a part of the second?

1 次查看(过去 30 天)
I have been given a peculiar task by my instructor. There are two K means code, I need to write a K means function which captures the functionality of both. The first was used for image segmentation and the second to K means cluster data points. I understand the algo in both but I dont understand how to use the X in function 1 by using the 2nd function.
Please help. New to MATLAB.
% function 1
function X = my_kmeans(F,K,iter)
CENTS = F( ceil(rand(K,1)*size(F,1)) ,:);
DAL = zeros(size(F,1),K+2);
for n = 1:iter
for i = 1:size(F,1)
for j = 1:K
DAL(i,j) = norm(F(i,:) - CENTS(j,:));
end
[Distance, CN] = min(DAL(i,1:K)); % 1:K are Distance from Cluster Centers 1:K
DAL(i,K+1) = CN; % K+1 is Cluster Label
DAL(i,K+2) = Distance; % K+2 is Minimum Distance
end
for i = 1:K
A = (DAL(:,K+1) == i); % Cluster K Points
CENTS(i,:) = mean(F(A,:)); % New Cluster Centers
if sum(isnan(CENTS(:))) ~= 0 % If CENTS(i,:) Is Nan Then Replace It With Random Point
NC = find(isnan(CENTS(:,1))); % Find Nan Centers
for Ind = 1:size(NC,1)
CENTS(NC(Ind),:) = F(randi(size(F,1)),:);
end
end
end
end
X = zeros(size(F));
for i = 1:K
idx = find(DAL(:,K+1) == i);
X(idx,:) = repmat(CENTS(i,:),size(idx,1),1);
end
end
% Function 2
function [means,Nmeans,membership] = my_kmeans_data(X,K,maxerr)
[Ndata, dims] = size(X);
dist = zeros(1,K);
means = zeros(K,dims);
if (nargout > 2)
membership = zeros(Ndata,1);
end
% Initial prototype assignment (arbitrary)
for i=1:K-1
means(i,:) = X(i,:);
end
means(K,:) = mean(X(K:Ndata,:));
cmp = 1 + maxerr;
while (cmp > maxerr)
% Sums (class) and data counters (Nclass) initialization
class = zeros(K,dims);
Nclass = zeros(K,1);
% Groups each elements to the nearest prototype
for i=1:Ndata
for j=1:K
% Euclidean distance from data to each prototype
dist(j) = norm(X(i,:)-means(j,:))^2;
end
% Find indices of minimum distance
index_min = find(~(dist-min(dist)));
% If there are multiple min distances, decide randomly
index_min = index_min(ceil(length(index_min)*rand));
if (nargout > 2)
membership(i) = index_min;
end
class(index_min,:) = class(index_min,:) + X(i,:);
Nclass(index_min) = Nclass(index_min) + 1;
end
for i=1:K
class(i,:) = class(i,:) / Nclass(i);
end
% Compare results with previous iteration
cmp = 0;
for i=1:K
cmp = norm(class(i,:)-means(i,:));
end
% Prototype update
means = class;
end
Nmeans = Nclass;
end
  1 个评论
Subhransu Sekhar Bhattacharjee
Note both the codes belong to respecctive owners and I do not own the copyright. I am just using them for academic purpose.

请先登录,再进行评论。

回答(1 个)

Akanksha Shrimal
Akanksha Shrimal 2022-4-27
Hi,
Can you clearly explain what exactly you mean by using X in function 1 by using the 2nd function.
What use case are you trying to achieve with this.

产品

Community Treasure Hunt

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

Start Hunting!

Translated by