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

1 view (last 30 days)
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,:));
[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
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)),:);
X = zeros(size(F));
for i = 1:K
idx = find(DAL(:,K+1) == i);
X(idx,:) = repmat(CENTS(i,:),size(idx,1),1);
% 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);
% Initial prototype assignment (arbitrary)
for i=1:K-1
means(i,:) = X(i,:);
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;
% 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;
class(index_min,:) = class(index_min,:) + X(i,:);
Nclass(index_min) = Nclass(index_min) + 1;
for i=1:K
class(i,:) = class(i,:) / Nclass(i);
% Compare results with previous iteration
cmp = 0;
for i=1:K
cmp = norm(class(i,:)-means(i,:));
% Prototype update
means = class;
Nmeans = Nclass;
  1 Comment
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.

Sign in to comment.

Answers (1)

Akanksha Shrimal
Akanksha Shrimal on 27 Apr 2022
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!