聚类分析matlab程序设计代码
kmeans和cmeans matlab代码

K-means和c-means算法是聚类分析中常用的两种算法,在MATLAB软件中可以通过编写相应的代码来实现这两种算法。
下面将分别介绍K-means算法和c-means算法的原理以及在MATLAB中的实现代码。
一、K-means算法原理及MATLAB代码实现K-means算法是一种基于距离的聚类算法,其原理主要包括初始化聚类中心、计算样本点到各个聚类中心的距离、更新聚类中心和迭代等步骤。
以下是K-means算法在MATLAB中的实现代码:1. 初始化聚类中心```matlabfunction [centers] = initCenters(data, k)centers = data(randperm(size(data, 1), k), :);end```2. 计算样本点到各个聚类中心的距离```matlabfunction [distances] = calculateDistances(data, centers)distances = pdist2(data, centers, 'euclidean');end```3. 更新聚类中心```matlabfunction [newCenters] = updateCenters(data, labels, k) newCenters = zeros(k, size(data, 2));for i = 1:knewCenters(i, :) = mean(data(labels == i, :));endend```4. 迭代```matlabfunction [labels, centers] = kMeans(data, k, maxIter) centers = initCenters(data, k);for iter = 1:maxIterdistances = calculateDistances(data, centers);[~, labels] = min(distances, [], 2);newCenters = updateCenters(data, labels, k);if isequal(newCenters, centers)break;endcenters = newCenters;endend```以上即是K-means算法在MATLAB中的实现代码,可以根据实际需求调用相应的函数来进行聚类分析。
matlab中kmeans代码

一、前言在数据分析和机器学习领域,k-means算法是一种常用的聚类算法,它可以将数据集分成不同的簇,每个簇内的数据点彼此相似,而不同簇之间的数据点相似度较低。
在matlab中,可以利用其强大的数学计算功能来实现k-means聚类算法。
本文将介绍如何在matlab中编写k-means聚类算法的代码。
二、matlab中的k-means算法1. 初始化数据集需要准备好要进行聚类分析的数据集。
这些数据可以是一组二维或多维的点,代表不同的特征。
在matlab中,可以使用矩阵来表示这些数据集,每一行代表一个数据点,每一列代表一个特征。
2. 设置聚类数量在进行k-means聚类算法之前,需要先确定要分成的簇的数量。
这个数量可以根据业务需求或者领域知识来确定。
在matlab中,可以使用kmeans函数来执行聚类分析,该函数需要指定数据集和聚类数量。
3. 运行k-means算法一旦准备好了数据集和聚类数量,就可以调用matlab中的kmeans 函数来执行k-means算法。
该函数会根据数据集和聚类数量来计算出不同簇的中心点,并将每个数据点分配到最近的簇中。
4. 可视化聚类结果完成k-means算法之后,可以将聚类结果可视化出来,以便更直观地理解不同簇之间的分布情况。
在matlab中,可以使用plot函数来绘制数据点和聚类中心,以及不同簇的分布情况。
三、示例代码以下是一个简单的matlab代码示例,演示了如何使用kmeans函数来执行k-means聚类算法:```matlab读取数据data = load('data.txt');设置聚类数量k = 3;运行k-means算法[idx, centers] = kmeans(data, k);可视化聚类结果figure;gscatter(data(:,1), data(:,2), idx);hold on;plot(centers(:,1), centers(:,2), 'kx', 'MarkerSize', 15, 'LineWidth', 3); ```以上代码首先读取了名为data.txt的数据集,然后设置了聚类数量为3。
matlab kmeans聚类算法代码

一、引言在机器学习和数据分析中,聚类是一种常用的数据分析技术,它可以帮助我们发现数据中的潜在模式和结构。
而k均值(k-means)聚类算法作为一种经典的聚类方法,被广泛应用于各种领域的数据分析和模式识别中。
本文将介绍matlab中k均值聚类算法的实现和代码编写。
二、k均值(k-means)聚类算法简介k均值聚类算法是一种基于距离的聚类算法,它通过迭代的方式将数据集划分为k个簇,每个簇内的数据点与该簇的中心点的距离之和最小。
其基本思想是通过不断调整簇的中心点,使得簇内的数据点与中心点的距离最小化,从而实现数据的聚类分布。
三、matlab实现k均值聚类算法步骤在matlab中,实现k均值聚类算法的步骤如下:1. 初始化k个簇的中心点,可以随机选择数据集中的k个点作为初始中心点。
2. 根据每个数据点与各个簇中心点的距离,将数据点分配给距离最近的簇。
3. 根据每个簇的数据点重新计算该簇的中心点。
4. 重复步骤2和步骤3,直到簇的中心点不再发生变化或者达到预定的迭代次数。
在matlab中,可以通过以下代码实现k均值聚类算法:```matlab设置参数k = 3; 设置簇的个数max_iter = 100; 最大迭代次数初始化k个簇的中心点centroids = datasample(data, k, 'Replace', false);for iter = 1:max_iterStep 1: 计算每个数据点与簇中心点的距离distances = pdist2(data, centroids);Step 2: 分配数据点给距离最近的簇[~, cluster_idx] = min(distances, [], 2);Step 3: 重新计算每个簇的中心点for i = 1:kcentroids(i, :) = mean(data(cluster_idx == i, :)); endend得到最终的聚类结果cluster_result = cluster_idx;```四、代码解释上述代码实现了k均值聚类算法的基本步骤,其中包括了参数设置、簇中心点的初始化、迭代过程中的数据点分配和中心点更新。
matlab、lingo程序代码14-模糊聚类(聚类分析)

模糊聚类function c=fuz_hc(a,b)%模糊矩阵的合成运算程序%输入模糊矩阵a,b,输出合成运算结果cm=size(a,1);n=size(b,2);p=size(a,2);%错误排除if size(a,2)~=size(b,1)disp('输入数据错误!');return;end%合成运算for i=1:mfor j=1:nfor k=1:ptemp(k)=min(a(i,k),b(k,j));endc(i,j)=max(temp);endenddisp('模糊矩阵a与b作合成运算后结果矩阵c为:'); c% 求模糊等价矩阵function r_d=mhdj(r)[m,n]=size(r);for i=1:nfor j=1:nfor k=1:nr1(i,j,k)=min(r(i,k),r(k,j));endr1max(i,j)=r1(i,j,1);endendfor i=1:nfor j=1:nfor k=1:nif r1(i,j,k)>r1max(i,j)r1max(i,j)=r1(i,j,k);endendr_d(i,j)=r1max(i,j);endend%模糊聚类程序function f=mujl(x,lamda)%输入原始数据以及lamda的值if lamda>1disp('error!') %错误处理end[n,m]=size(x);y=pdist(x);disp('欧式距离矩阵:');dist=squareform(y) %欧氏距离矩阵dmax=dist(1,1);for i=1:nfor j=1:nif dist(i,j)>dmaxdmax=dist(i,j);endendenddisp('处理后的欧氏距离矩阵,其特点为每项元素均不超过1:');sdist=dist/dmax %使距离值不超过1disp('模糊关系矩阵:');r=ones(n,n)-sdist %计算对应的模糊关系矩阵t=mhdj(r);le=t-r;while all(all(le==0)==0)==1 %如果t与r相等,则继续求r乘以r r=t;t=mhdj(r);le=t-r;enddisp('模糊等价矩阵为:')tfor i=1:nk=1;for j=1:nif t(i,j)>=lamdagroup(i,k)=j;k=k+1;endendenddisp('聚类结果如下(数字0为自动填充数据,不是样本序号):') group(1,:)for i=2:nk=0;for j=1:i-1if all(group(i,:)==group(j,:))==1 %两行值完全相等,不输出k=1;break;endendif k==0disp(group(i,:)) %仅输出不重复的分类endend%模糊聚类程序function f=mujl(x,lamda)%输入原始数据以及lamda的值if lamda>1disp('error!') %错误处理end[n,m]=size(x);xmax=max(x);xmin=min(x);x=(x-xmin(ones(n,1),:))./(xmax(ones(n,1),:)-xmin(ones(n,1),:))y=pdist(x);disp('欧式距离矩阵:');dist=squareform(y) %欧氏距离矩阵dmax=dist(1,1);for i=1:nfor j=1:nif dist(i,j)>dmaxdmax=dist(i,j);endendenddisp('处理后的欧氏距离矩阵,其特点为每项元素均不超过1:');sdist=dist/dmax %使距离值不超过1disp('模糊关系矩阵:');r=ones(n,n)-sdist %计算对应的模糊关系矩阵t=mhdj(r);le=t-r;while all(all(le==0)==0)==1 %如果t与r相等,则继续求r乘以r r=t;t=mhdj(r);le=t-r;enddisp('模糊等价矩阵为:')tfor i=1:nk=1;for j=1:nif t(i,j)>=lamdagroup(i,k)=j;k=k+1;endendenddisp('聚类结果如下(数字0为自动填充数据,不是样本序号):') group(1,:)gru_val=1;for i=2:nk=0;for j=1:i-1if all(group(i,:)==group(j,:))==1 %两行值完全相等,不输出k=1;break;endendif k==0disp('第i类样本序号:'),igru_val=gru_val+1;disp(group(i,:)) %仅输出不重复的分类endendgru_val。
用matlab做聚类分析

用matlab做聚类分析转载一:MATLAB提供了两种方法进行聚类分析:1、利用clusterdata 函数对数据样本进行一次聚类,这个方法简洁方便,其特点是使用范围较窄,不能由用户根据自身需要来设定参数,更改距离计算方法;2、分步聚类:(1)用pdist函数计算变量之间的距离,找到数据集合中两辆变量之间的相似性和非相似性;(2)用linkage函数定义变量之间的连接;(3)用cophenetic函数评价聚类信息;(4)用cluster函数进行聚类。
下边详细介绍两种方法:1、一次聚类Clusterdata函数可以视为pdist、linkage与cluster的综合,一般比较简单。
【clusterdata函数:调用格式:T=clusterdata(X,cutoff)等价于Y=pdist(X,’euclid’); Z=linkage(Y,’single’); T=cluster(Z,cutoff) 】2、分步聚类(1)求出变量之间的相似性用pdist函数计算出相似矩阵,有多种方法可以求距离,若此前数据还未无量纲化,则可用zscore函数对其标准化【pdist函数:调用格式:Y=pdist(X,’metric’)说明:X是M*N矩阵,为由M个样本组成,每个样本有N个字段的数据集metirc取值为:’euclidean’:欧氏距离(默认)‘seuclidean’:标准化欧氏距离;‘mahalanobis’:马氏距离…】pdist生成一个M*(M-1)/2个元素的行向量,分别表示M个样本两两间的距离。
这样可以缩小保存空间,不过,对于读者来说却是不好操作,因此,若想简单直观的表示,可以用squareform函数将其转化为方阵,其中x(i,j)表示第i个样本与第j个样本之的距离,对角线均为0.(2)用linkage函数来产生聚类树【linkage函数:调用格式:Z=linkage(Y,’method’)说明:Y为pdist函数返回的M*(M-1)/2个元素的行向量,method可取值:‘single’:最短距离法(默认);’complete’:最长距离法;‘average’:未加权平均距离法;’weighted’:加权平均法‘centroid’:质心距离法;‘median’:加权质心距离法;‘ward’:内平方距离法(最小方差算法)】返回的Z为一个(M-1)*3的矩阵,其中前两列为索引标识,表示哪两个序号的样本可以聚为同一类,第三列为这两个样本之间的距离。
K-Means聚类算法若干实例Matlab代码

要用matlab做聚类,找了几个资源,列在这里。
一、方法1: 用matlab自带的函数,IDX = kmeans(X,k)二、参照一段网友写的代码function y=kMeansCluster(m,k,isRand)%%%%%%%%%%%%%%%%%% kMeansCluster - Simple k means clustering algorithm% Author: Kardi Teknomo, Ph.D.%% Purpose: classify the objects in data matrix based on the attributes% Criteria: minimize Euclidean distance between centroids and object points% For more explanation of the algorithm, see /kardi/tutorial/kMean/index.html% Output: matrix data plus an additional column represent the group of each object%% Example: m = [ 1 1; 2 1; 4 3; 5 4] or in a nice form% m = [ 1 1;% 2 1;% 4 3;% 5 4]% k = 2% kMeansCluster(m,k) produces m = [ 1 1 1;% 2 1 1;% 4 3 2;% 5 4 2]% Input:% m - required, matrix data: objects in rows and attributes in columns % k - optional, number of groups (default = 1)% isRand - optional, if using random initialization isRand=1, otherwise input any number (default)% it will assign the first k data as initial centroids%% Local Variables% f - row number of data that belong to group i% c - centroid coordinate size (1:k, 1:maxCol)% g - current iteration group matrix size (1:maxRow)% i - scalar iterator% maxCol - scalar number of rows in the data matrix m = number of attributes % maxRow - scalar number of columns in the data matrix m = number of objects % temp - previous iteration group matrix size (1:maxRow)% z - minimum value (not needed) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%if nargin<3, isRand=0; endif nargin<2, k=1; end[maxRow, maxCol]=size(m)if maxRow<=k,y=[m, 1:maxRow]else% initial value of centroidif isRand,p = randperm(size(m,1)); % random initializationfor i=1:kc(i,:)=m(p(i),:)endelsefor i=1:kc(i,:)=m(i,:) % sequential initializationendendtemp=zeros(maxRow,1); % initialize as zero vectorwhile 1,d=DistMatrix(m,c); % calculate objcets-centroid distances[z,g]=min(d,[],2); % find group matrix gif g==temp,break; % stop the iterationelsetemp=g; % copy group matrix to temporary variableendfor i=1:kf=find(g==i);if f % only compute centroid if f is not emptyc(i,:)=mean(m(find(g==i),:),1);endendendy=[m,g];endThe Matlab function kMeansCluster above call function DistMatrix as shown in the code below. It works for multi-dimensional Euclidean distance. Learn about other type of distance here.function d=DistMatrix(A,B)%%%%%%%%%%%%%%%%%%%%%%%%%% DISTMATRIX return distance matrix between points in A=[x1 y1 ... w1] and in B=[x2 y2 (2)% Copyright (c) 2005 by Kardi Teknomo, /kardi/%% Numbers of rows (represent points) in A and B are not necessarily the same.% It can be use for distance-in-a-slice (Spacing) or distance-between-slice (Headway),%% A and B must contain the same number of columns (represent variables of n dimensions),% first column is the X coordinates, second column is the Y coordinates, and so on.% The distance matrix is distance between points in A as rows% and points in B as columns.% example: Spacing= dist(A,A)% Headway = dist(A,B), with hA ~= hB or hA=hB% A=[1 2 3; 4 5 6; 2 4 6; 1 2 3]; B=[4 5 1; 6 2 0]% dist(A,B)= [ 4.69 5.83;% 5.00 7.00;% 5.48 7.48;% 4.69 5.83]%% dist(B,A)= [ 4.69 5.00 5.48 4.69;% 5.83 7.00 7.48 5.83]%%%%%%%%%%%%%%%%%%%%%%%%%%%[hA,wA]=size(A);[hB,wB]=size(B);if wA ~= wB, error(' second dimension of A and B must be the same'); endfor k=1:wAC{k}= repmat(A(:,k),1,hB);D{k}= repmat(B(:,k),1,hA);endS=zeros(hA,hB);for k=1:wAS=S+(C{k}-D{k}').^2;endd=sqrt(S);三、另外一个网友写的代码%这是一个简单的k均值聚类批处理函数%待分类的样本x=mvnrnd(mu,siguma,20)%idx3=kmeans(x,3,'distance','city');或者%idx4=kmeans(x,4,'dist','city','display','iter');这个可以显示出每次迭代的距离和%显示分类轮廓图[silh4,h]=silhouette(x,idx4,'city');xlable('silhouette% value');ylable('cluster')%mean(silh5) 结果越接近1越好mu1=[1,1];sigma1=[0.5 0;0 0.5];x1=mvnrnd(mu1,sigma1,10);mu2=[7,7];sigma2=[0.5 0;0 0.5];x2=mvnrnd(mu2,sigma2,10);x=[x1;x2]plot(x(:,1),x(:,2),'bo');[idx2,c]=kmeans(x,2,'dist','city','display','iter');figure(2);[silh2,h]=silhouette(x,idx2,'city');%xlable('silhouette value')%ylable('cluster')figure(3);plot(x(idx2==1,1),x(idx2==1,2),'r+',x(idx2==2,1),x(idx2==2,2),'b.');'分类水平:(1为最好):'a=mean(silh2);a'图心矩阵为:'c。
matlab做聚类分析

matlab做聚类分析Matlab提供了两种方法进行聚类分析。
一种是利用 clusterdata函数对样本数据进行一次聚类,其缺点为可供用户选择的面较窄,不能更改距离的计算方法;另一种是分步聚类:(1)找到数据集合中变量两两之间的相似性和非相似性,用pdist函数计算变量之间的距离;(2)用 linkage函数定义变量之间的连接;(3)用 cophenetic函数评价聚类信息;(4)用cluster函数创建聚类。
1.Matlab中相关函数介绍1.1 pdist函数调用格式:Y=pdist(X,’metric’)说明:用‘metric’指定的方法计算 X 数据矩阵中对象之间的距离。
’X:一个m×n的矩阵,它是由m个对象组成的数据集,每个对象的大小为n。
metric’取值如下:‘euclidean’:欧氏距离(默认);‘seuclidean’:标准化欧氏距离;‘mahalanobis’:马氏距离;‘cityblock’:布洛克距离;‘minkowski’:明可夫斯基距离;‘cosine’:‘correlation’:‘hamming’:‘jaccard’:‘chebychev’:Chebychev距离。
1.2 squareform函数调用格式:Z=squareform(Y,..)说明:强制将距离矩阵从上三角形式转化为方阵形式,或从方阵形式转化为上三角形式。
1.3 linkage函数调用格式:Z=linkage(Y,’method’)说明:用‘method’参数指定的算法计算系统聚类树。
Y:pdist函数返回的距离向量;method:可取值如下:‘single’:最短距离法(默认);‘complete’:最长距离法;‘average’:未加权平均距离法;‘weighted’:加权平均法;‘centroid’:质心距离法;‘median’:加权质心距离法;‘ward’:内平方距离法(最小方差算法)返回:Z为一个包含聚类树信息的(m-1)×3的矩阵。
matlab中kmeans代码

matlab中kmeans代码kmeans算法是一种常用的聚类分析方法,在matlab中有相应的代码实现。
本文将介绍kmeans算法的原理和用法,并以matlab中的kmeans代码为例进行演示和讲解。
kmeans算法是一种无监督学习算法,用于将一组数据分成多个簇。
其基本思想是通过计算数据点之间的距离,将相似的数据点归为同一簇。
kmeans算法的核心是确定簇的个数和簇中心点的位置。
在matlab中,使用kmeans算法可以通过调用kmeans函数来实现。
该函数的基本语法为:[idx, C] = kmeans(X, k)其中,X是一个n×d的矩阵,表示n个数据点的d维特征向量;k 是簇的个数;idx是一个n×1的向量,表示每个数据点所属的簇的索引;C是一个k×d的矩阵,表示每个簇的中心点的位置。
下面我们通过一个具体的例子来说明如何使用matlab中的kmeans 函数进行聚类分析。
假设我们有一组二维数据,我们希望将其分成两个簇。
首先,我们需要生成数据。
在matlab中可以使用randn函数生成服从正态分布的数据。
我们可以使用如下代码生成100个服从正态分布的数据点:```matlabX = [randn(50,2)+1; randn(50,2)-1];```然后,我们可以调用kmeans函数进行聚类分析。
假设我们希望将数据分成两个簇,可以使用如下代码:```matlabk = 2;[idx, C] = kmeans(X, k);```接下来,我们可以根据聚类结果将数据点可视化。
可以使用scatter函数绘制散点图,其中不同的簇使用不同的颜色表示。
代码如下:```matlabfigure;scatter(X(:,1), X(:,2), 50, idx, 'filled');hold on;scatter(C(:,1), C(:,2), 100, 'k', 'filled');```运行上述代码后,我们将得到一个散点图,其中不同的颜色表示不同的簇,黑色的点表示簇中心。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
function varargout = lljuleifenxi(varargin)% LLJULEIFENXI MATLAB code for lljuleifenxi.fig% LLJULEIFENXI, by itself, creates a new LLJULEIFENXI or raises the existing% singleton*.%% H = LLJULEIFENXI returns the handle to a new LLJULEIFENXI or the handle to% the existing singleton*.%% LLJULEIFENXI('CALLBACK',hObject,eventData,handles,...) calls the local% function named CALLBACK in LLJULEIFENXI.M with the given input arguments.%% LLJULEIFENXI('Property','Value',...) creates a new LLJULEIFENXI or raises the% existing singleton*. Starting from the left, property value pairs are % applied to the GUI before lljuleifenxi_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to lljuleifenxi_OpeningFcn via varargin. %% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)".%% See also: GUIDE, GUIDATA, GUIHANDLES% Edit the above text to modify the response to help lljuleifenxi% Last Modified by GUIDE v2.5 07-Jan-2015 18:18:25% Begin initialization code - DO NOT EDITgui_Singleton = 1;gui_State = struct('gui_Name', mfilename, ...'gui_Singleton', gui_Singleton, ...'gui_OpeningFcn', @lljuleifenxi_OpeningFcn, ...'gui_OutputFcn', @lljuleifenxi_OutputFcn, ...'gui_LayoutFcn', [] , ...'gui_Callback', []);if nargin && ischar(varargin{1})gui_State.gui_Callback = str2func(varargin{1});endif nargout[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});elsegui_mainfcn(gui_State, varargin{:});end% End initialization code - DO NOT EDIT% --- Executes just before lljuleifenxi is made visible.function lljuleifenxi_OpeningFcn(hObject, eventdata, handles, varargin)% This function has no output args, see OutputFcn.% hObject handle to figure% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)% varargin command line arguments to lljuleifenxi (see VARARGIN)% Choose default command line output for lljuleifenxihandles.output = hObject;% Update handles structureguidata(hObject, handles);% UIWAIT makes lljuleifenxi wait for user response (see UIRESUME)% uiwait(handles.figure1);% --- Outputs from this function are returned to the command line.function varargout = lljuleifenxi_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT);% hObject handle to figure% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)% Get default command line output from handles structurevarargout{1} = handles.output;% --- Executes during object creation, after setting all properties. function edit6_CreateFcn(hObject, eventdata, handles)% hObject handle to edit6 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles empty - handles not created until after all CreateFcns called function input_data_Callback(hObject, eventdata, handles)% hObject handle to input_data (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)% Hints: get(hObject,'String') returns contents of input_data as text% str2double(get(hObject,'String')) returns contents of input_data as a double% --- Executes during object creation, after setting all properties. function input_data_CreateFcn(hObject, eventdata, handles)% hObject handle to input_data (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows.% See ISPC and COMPUTER.if ispc && isequal(get(hObject,'BackgroundColor'),get(0,'defaultUicontrolBackgroundColor'))set(hObject,'BackgroundColor','white');endfunction input_obj_num_Callback(hObject, eventdata, handles)% hObject handle to input_obj_num (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)% Hints: get(hObject,'String') returns contents of input_obj_num as text % str2double(get(hObject,'String')) returns contents ofinput_obj_num as a double% --- Executes during object creation, after setting all properties. function input_obj_num_CreateFcn(hObject, eventdata, handles)% hObject handle to input_obj_num (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows.% See ISPC and COMPUTER.if ispc && isequal(get(hObject,'BackgroundColor'),get(0,'defaultUicontrolBackgroundColor'))set(hObject,'BackgroundColor','white');endfunction input_var_num_Callback(hObject, eventdata, handles)% hObject handle to input_var_num (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)% Hints: get(hObject,'String') returns contents of input_var_num as text % str2double(get(hObject,'String')) returns contents ofinput_var_num as a double% --- Executes during object creation, after setting all properties. function input_var_num_CreateFcn(hObject, eventdata, handles)% hObject handle to input_var_num (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows.% See ISPC and COMPUTER.if ispc && isequal(get(hObject,'BackgroundColor'),get(0,'defaultUicontrolBackgroundColor'))set(hObject,'BackgroundColor','white');end% --- Executes on selection change in popm_class_method.function popm_class_method_Callback(hObject, eventdata, handles)% hObject handle to popm_class_method (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)% Hints: contents = cellstr(get(hObject,'String')) returnspopm_class_method contents as cell array% contents{get(hObject,'Value')} returns selected item frompopm_class_method% --- Executes during object creation, after setting all properties. function popm_class_method_CreateFcn(hObject, eventdata, handles)% hObject handle to popm_class_method (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows.% See ISPC and COMPUTER.if ispc && isequal(get(hObject,'BackgroundColor'),get(0,'defaultUicontrolBackgroundColor'))set(hObject,'BackgroundColor','white');end% --- Executes on selection change in popm_cluster_method.function popm_cluster_method_Callback(hObject, eventdata, handles)% hObject handle to popm_cluster_method (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)% Hints: contents = cellstr(get(hObject,'String')) returnspopm_cluster_method contents as cell array% contents{get(hObject,'Value')} returns selected item frompopm_cluster_method% --- Executes during object creation, after setting all properties. function popm_cluster_method_CreateFcn(hObject, eventdata, handles)% hObject handle to popm_cluster_method (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows.% See ISPC and COMPUTER.if ispc && isequal(get(hObject,'BackgroundColor'),get(0,'defaultUicontrolBackgroundColor'))set(hObject,'BackgroundColor','white');end% --- Executes on mouse press over axes background.function axes_ButtonDownFcn(hObject, eventdata, handles)% hObject handle to axes (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)% --- Executes during object deletion, before destroying properties. function axes_DeleteFcn(hObject, eventdata, handles)% hObject handle to axes (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)% --- Executes on button press in btn_start.function btn_start_Callback(hObject, eventdata, handles)% hObject handle to btn_start (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)str_num_obj = get(handles.input_obj_num,'String');str_num_var = get(handles.input_var_num,'String');exp = '\D+';isNum =(isempty(regexp(str_num_obj,exp))&&isempty(regexp(str_num_obj,exp)));if(isNum)num_obj = str2num(str_num_obj);num_var = str2num(str_num_var);trysource_data = str2num(get(handles.input_data,'String'));val_class_method = get(handles.popm_class_method,'Value');% return the selected item from pop_menustr_class_method = get(handles.popm_class_method,'String');% return the contents of the pop_menu% this is the default valuehandles.current_method = 'cityblock';switch str_class_method{val_class_method} % it is the current selected item (String)case'¾ø¶ÔÖµ¾àÀë'handles.current_method = 'cityblock';case'ãɿɷò˹»ù¾àÀë'handles.current_method = 'minkowski';case'ÂíÊϾàÀë'handles.current_method = 'mahalanobis';case'×Ô¶¨Òå¾àÀë'handles.current_method = 'myDistFun';% alert to user to edit custome function in the myDistFun.m and the% default is use the euclidean distmH = msgbox('you could custom the distance function in the file myDistFun,if not,the default is the City block distance','attention');uiwait(mH);case'¼Ð½ÇÓàÏÒ'handles.current_method = 'cosine';case'Ïà¹ØÏµÊý'handles.current_method = 'correlation';endval_cluster_method = get(handles.popm_cluster_method,'Value');% return the selected item from pop_menustr_cluster_method = get(handles.popm_cluster_method,'String');% return the contents of the pop_menu% this is the default valuehandles.current_cluster_method = 'single';switch str_cluster_method{val_cluster_method}case'×î¶Ì¾àÀë·¨ 'handles.current_cluster_method = 'single';case'×¾àÀë·¨'handles.current_cluster_method = 'complete';case'Öмä¾àÀë·¨'handles.current_cluster_method = 'median';case'ÖØÐÄ·¨'handles.current_cluster_method = 'centroid';case'ÀàÆ½¾ù·¨'handles.current_cluster_method = 'average';case'Àë²îƽ·½ºÍ·¨'handles.current_cluster_method = 'ward';end%% check the datareal_rows = size(source_data,1);real_cols = size(source_data,2);if(real_rows ~= num_obj || real_cols ~= num_var)% alert to user that the data dont't matchingmH = msgbox('the size of your input data is notmatching','attention');uiwait(mH);else%% begin cluster and show the cluster tree on the axespdist_method = handles.current_method;if(strcmp(pdist_method,'myDistFun'))dist_matr = pdist(source_data,@myDistFun);elsedist_matr = pdist(source_data,pdist_method);endlinkage_method = handles.current_cluster_method;cluster_result = linkage(dist_matr,linkage_method);axes(handles.axes);dendrogram(cluster_result);endcatch errmH = msgbox('please input the correct data!');uiwait(mH)endelsemH = msgbox('please input the correct data!');uiwait(mH);end% --- Executes during object creation, after setting all properties. function tittle_CreateFcn(hObject, eventdata, handles)% hObject handle to tittle (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles empty - handles not created until after all CreateFcns called function Z = myDistFun( X,Y )%the custom distance function% where X is a 1-by-n vector,and Y is an m-by-n matrix,% myDistFun must return an m-by-1 vector of distances Z,% whose kth element is the distance between X and Y(k,:).%% this is the City block distance definitionXX = repmat(X,size(Y,1),1);Z = sum(abs(XX - Y),2);%% you can definite your own distance function hereend。