Reputation: 139
Actually what I am doing is that I want to write my own function of k-means clustering. But, for giving the initial inputs, I don't know how to do that in Matlab. What I mean is, one input of the function is the number of cluster centers, k, and then we need to input the k initial values the function will use in the first iteration. But the k may change and the number of initial values will change. So how can I do this using Matlab. I want the input to be an integer k, and k initial values. With different k, different number of initial inputs changes, so what I can do?
Thanks in advance!!
Upvotes: 0
Views: 54
Reputation: 2441
With variable nuber of inputs:
function retVal = kMeans(varargin)
% at least k has to be given
if length(varargin) < 1
error('Wrong number of arguments given');
end
k = varargin{1};
disp(['K: ',num2str(k)]);
%check if k+1 inputs are given
if length(varargin) ~= k+1
error('Wrong number of arguments given');
end
% process inputs
for i = 1+(1:k)
center = varargin{i};
disp(['Input Center ',num2str(i-1),' : ', num2str(center)]);
end
end
When called with kMeans(2,[1,2],[3,4])
it outputs:
K: 2
Input Center 1 : 1 2
Input Center 2 : 3 4
Upvotes: 0
Reputation: 2441
why do you need k+1 inputs? Can't you just use one input? For example with clustering in 2 dimensions:
function [ returnValues] = kMeans( centers)
% get number of cluster centers
k = size(centers,1);
for i = 1:k
% select each center individually:
center = centers(i,:);
% process
end
An example call with three cluster centers [1,2] , [3,4] and [5,6] would then be:
values = kMeans([1,2;3,4;5,6]);
Upvotes: 1