复杂网络聚类系数和平均路径长度计算的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。
度,聚类系数,平均路径长度程序

function [DeD,aver_DeD]=Degree_Distribution(A)%% 求网络图中各节点的度及度的分布曲线%% 求解算法:求解每个节点的度,再按发生频率即为概率,求P(k)%A————————网络图的邻接矩阵%DeD————————网络图各节点的度分布%aver_DeD———————网络图的平均度N=size(A,2);DeD=zeros(1,N);for i=1:N% DeD(i)=length(find((A(i,:)==1)));DeD(i)=sum(A(i,:));endaver_DeD=mean(DeD);if sum(DeD)==0disp('该网络图只是由一些孤立点组成');return;elsefigure;bar([1:N],DeD);xlabel('节点编号n');ylabel('各节点的度数K');title('网络图中各节点的度的大小分布图');endfigure;M=max(DeD);for i=1:M+1; %网络图中节点的度数最大为M,但要同时考虑到度为0的节点的存在性N_DeD(i)=length(find(DeD==i-1));endP_DeD=zeros(1,M+1);P_DeD(:)=N_DeD(:)./sum(N_DeD);bar([0:M],P_DeD,'r');xlabel('节点的度K');ylabel('节点度为K的概率P(K)');title('网络图中节点度的概率分布图');function [C,aver_C]=Clustering_Coefficient(A)%% 求网络图中各节点的聚类系数及整个网络的聚类系数%% 求解算法:求解每个节点的聚类系数,找某节点的所有邻居,这些邻居节点构成一个子图%% 从A中抽出该子图的邻接矩阵,计算子图的边数,再根据聚类系数的定义,即可算出该节点的聚类系数%A————————网络图的邻接矩阵%C————————网络图各节点的聚类系数%aver———————整个网络图的聚类系数N=size(A,2);C=zeros(1,N);for i=1:Naa=find(A(i,:)==1); %寻找子图的邻居节点if isempty(aa)disp(['节点',int2str(i),'为孤立节点,其聚类系数赋值为0']);C(i)=0;elsem=length(aa);if m==1disp(['节点',int2str(i),'只有一个邻居节点,其聚类系数赋值为0']);C(i)=0;elseB=A(aa,aa); % 抽取子图的邻接矩阵C(i)=length(find(B==1))/(m*(m-1));endendendaver_C=mean(C);function [D,aver_D]=Aver_Path_Length(A)%% 求复杂网络中两节点的距离以及平均路径长度%% 求解算法:首先利用Floyd算法求解出任意两节点的距离,再求距离的平均值得平均路径长度% A————————网络图的邻接矩阵% D————————返回值:网络图的距离矩阵% aver_D———————返回值:网络图的平均路径长度N=size(A,2);D=A;D(find(D==0))=inf; %将邻接矩阵变为邻接距离矩阵,两点无边相连时赋值为inf,自身到自身的距离为0.for i=1:ND(i,i)=0;endfor k=1:N %Floyd算法求解任意两点的最短距离for i=1:Nfor j=1:Nif D(i,j)>D(i,k)+D(k,j)D(i,j)=D(i,k)+D(k,j);endendendendaver_D=sum(sum(D))/(N*(N-1)); %平均路径长度if aver_D==infdisp('该网络图不是连通图');end%% 算法2:用时间量级O(MN)的广度优先算法求解一个含N个节点和M条边的网络图的平均路径长度。
复杂网络聚类系数和平均路径长度计算的MATLAB源代码

复杂网络聚类系数和平均路径长度计算的MATLAB源代码复杂网络的聚类系数和平均路径长度是度量网络结构特征的重要指标。
下面是MATLAB源代码,用于计算复杂网络的聚类系数和平均路径长度。
首先,我们需要定义一个函数,用于计算节点的聚集系数。
这个函数的输入参数是邻接矩阵和节点的索引,输出参数是节点的聚类系数。
```matlabfunction cc = clustering_coefficient(adj_matrix, node_index) neighbors = find(adj_matrix(node_index, :));k = length(neighbors);if k < 2cc = 0;elseconnected_count = 0;for i = 1:k-1for j = i+1:kif adj_matrix(neighbors(i), neighbors(j))connected_count = connected_count + 1;endendendcc = 2 * connected_count / (k * (k - 1));endend```接下来,我们定义一个函数,用于计算整个网络的平均聚合系数。
```matlabfunction avg_cc = average_clustering_coefficient(adj_matrix) n = size(adj_matrix, 1);cc = zeros(n, 1);for i = 1:ncc(i) = clustering_coefficient(adj_matrix, i);endavg_cc = sum(cc) / n;end```然后,我们需要计算网络的平均最短路径长度。
这里我们使用了Floyd算法来计算每对节点之间的最短路径。
```matlabfunction avg_path_length =average_shortest_path_length(adj_matrix)n = size(adj_matrix, 1);dist_matrix =graphallshortestpaths(sparse(double(adj_matrix)));avg_path_length = sum(dist_matrix(:)) / (n^2 - n);end```最后,我们可以使用这些函数来计算一个复杂网络的聚类系数和平均路径长度。
节点重要度算法-MATLAB源代码

节点收缩算法:function Z=node(a,dy)%a为邻接矩阵a(a==inf)=0;a(~=0)=1;n=size(a,1);%矩阵维数Z=zeros(n,1);%节点重要度向量%由邻接矩阵a得到直接矩阵H%H表示c(i j)H=zeros(size(a));for i=1:nfor j=1:nif j==iH(i,j)=0;elseif a(I,j)==1H(i,j)=1;elseH(i,j)=inf;endendend%用Floyd法计算节点收缩前的最短就离矩阵D D=H;for k=1:nfor i=1:nfor j=1:nIf D(i,k)+D(k,j)<D(iI,j)D(i,j)=D(i,k)+D(k,j);endendendend%计算节点重要度D2=zeros(size(D));for i=1:n%得到与节点i邻接的节点向量II=zeros(1,0);T=0;for j=1:nif a(i,j)=1T=t+1;I=[i,j];endend%计算收缩后最短距离矩阵D2%D2为d’(pq) D为d(pq)for p=1:nfor q=1:nIf p~=1&q~=iIf D(p,i)+D(i,q)==D(p,q)D2(p,q)=D(p,q)-2;elseif D(p,i)+D(i,q)==D(p,q)+1D2(p,q)=D(p,q)-1;elseif D(p,i)+D(i,q)==D(p,q)+2D2(p,q)=D(p,q);endelseif p==i|q==iD2(p,q)=D(p,q)-1;elseD2(p,q)=0;endendendN3=n-t;%收缩后的节点数n3D3=D2;%计算收缩后的最短距离矩阵D3,D3为D D3(I,:)=[];%删除与节点i邻接的节点对应的行D3(:,I)=[];%删除与节点i邻接的节点对应的列%计算节点收缩后的节点重要度s=0;for p=1:n3for q=p:n3s=s+D3(p,q);endendl=s/(n3*(n3-1)/2);%为nZ(i)=1/(n3*l);end===================================节点介数=========================function B=betweenness_node(A,a)%%求网络节点介数,BY QiCheng%%思想:节点i、j间的距离等于节点i、k间距离与节点k、j间距离时,i、j间的最短路径经过k。
加权聚类系数和加权平均路径长度matlab代码

加权聚类系数和加权平均路径长度matlab代码(实用版)目录1.引言2.加权聚类系数和加权平均路径长度的定义和意义3.Matlab 代码实现4.结论正文一、引言在网络科学中,聚类系数和平均路径长度是两个重要的参数,用于描述网络的结构特性。
加权聚类系数和加权平均路径长度是在此基础上,对这两个参数进行加权处理,使得分析结果更加精确。
本文将介绍如何使用Matlab 代码实现加权聚类系数和加权平均路径长度的计算。
二、加权聚类系数和加权平均路径长度的定义和意义1.加权聚类系数加权聚类系数是用来衡量网络中节点之间联系紧密程度的参数。
其计算公式为:加权聚类系数 = (∑(权重^2)) / (∑(权重))其中,权重代表连接两个节点的边的权重。
2.加权平均路径长度加权平均路径长度是用来衡量网络中节点之间平均距离的参数。
其计算公式为:加权平均路径长度 = ∑(路径长度 * 权重) / ∑(权重)其中,路径长度代表从源节点到目标节点经过的边的权重之和,权重代表连接两个节点的边的权重。
三、Matlab 代码实现假设我们有一个邻接矩阵表示的网络,邻接矩阵如下:```A = [0, 1, 1, 0, 0, 1, 0, 1, 0, 0];```我们可以使用以下 Matlab 代码实现加权聚类系数和加权平均路径长度的计算:```matlab% 邻接矩阵A = [0, 1, 1, 0, 0, 1, 0, 1, 0, 0];% 计算加权聚类系数weight = A; % 假设权重与邻接矩阵相同clustering_coefficient = sum(weight.^2) / sum(weight);% 计算加权平均路径长度path_length = sum(sum(weight, 2) * weight) / sum(weight);```四、结论通过 Matlab 代码,我们可以方便地实现加权聚类系数和加权平均路径长度的计算。
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代码

聚类分析matlab代码聚类分析是一种机器学习方法,用于对数据进行分类,将相似的数据聚合在一起,产生有用的洞察和结论。
MATLAB是一个常用的数学计算软件,也可以用于聚类分析。
本文将介绍MATLAB中的聚类分析代码。
1. 数据准备首先,需要准备聚类分析所需的数据。
可以使用MATLAB内置的示例数据集,如鸢尾花数据集、手写数字数据集等。
也可以导入自己的数据集,例如Excel文件。
2. 数据前处理接下来,需要对数据进行前处理以便于聚类分析。
这可能包括数据清理、数据转换和特征提取。
例如,对于鸢尾花数据集,可以将花的特征信息(花瓣长度、花瓣宽度、花萼长度、花萼宽度)作为每个样本的特征。
3. 选择聚类算法MATLAB提供了多种聚类算法,可以根据数据类型和问题选择合适的算法。
常用的聚类算法包括K均值聚类、层次聚类、谱聚类等。
例如,对于鸢尾花数据集,可以使用K均值聚类算法。
4. 聚类分析一旦选择好算法,就可以开始聚类分析。
使用MATLAB的聚类算法函数进行聚类,例如kmeans函数进行K均值聚类。
函数需要输入样本数据、聚类数目等参数,并返回聚类结果。
5. 结果可视化最后,可以将聚类结果可视化,以便于理解和解释。
使用MATLAB的绘图函数,例如scatter函数或plot函数,将聚类结果表示在二维或三维图形上。
可以使用不同的颜色或符号表示不同的聚类簇。
下面是一个简单的MATLAB聚类分析代码,用于对鸢尾花数据集进行K均值聚类:% 导入鸢尾花数据集load fisheriris% 提取特征向量X = meas;% K均值聚类[idx, C] = kmeans(X, 3);% 绘制聚类结果figuregscatter(X(:,1),X(:,2),idx)hold onplot(C(:,1),C(:,2),'kx','LineWidth',2,'MarkerSize',10)legend('Cluster 1','Cluster 2','Cluster 3','Centroids','Location','NW') xlabel 'Sepal length';ylabel 'Sepal width';title 'K-means Clustering';。
聚类分析matlab程序设计代码

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。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
复杂网络聚类系数和平均路径长度计算的 MA TLAB 源代码申明:文章来自百度用户 carrot_hy复杂网络的代码总共是三个m文件,复制如下:第一个文件, CCM_ClusteringCoef.mfunction [Cp_Global, Cp_Nodal] = CCM_ClusteringCoef(gMatrix, Types)% CCM_ClusteringCoef calculates clustering coefficients.% Input:% gMatrix adjacency matrix% Types type of graph:'binary','weighted','directed','all'(default).% Usage:% [Cp_Global, Cp_Nodal] = CCM_ClusteringCoef(gMatrix, Types) returns% clustering coefficients for all nodes "Cp_Nodal" and average clustering % coefficient of network "Cp_Global".% Example:% G = CCM_TestGraph1('nograph');% [Cp_Global, Cp_Nodal] = CCM_ClusteringCoef(G);% Note:% 1) one node have vaule 0, while which only has a neighbour or none.% 2) The dircted network termed triplets that fulfill the follow condition % as non-vacuous: j->i->k and k->i-j,if don't satisfy with that as% vacuous, just like: j->i,k->i and i->j,i->k. and the closed triplets% only j->i->k == j->k and k->i->j == k->j.% 3) 'ALL' type network code from Mika Rubinov's BCT toolkit.% Refer:% [1] Barrat et al. (2004) The architecture of the complex weighted networks. % [2] Wasserman,S.,Faust,K.(1994) Social Network Analysis: Methods and % Applications.% [3] Tore Opsahl and Pietro Panzarasa (2009). "Clustering in Weighted% Networks". Social Networks31(2).% See also CCM_Transitivity% Written by Yong Liu, Oct,2007% Center for Computational Medicine (CCM),% National Laboratory of Pattern Recognition (NLPR),% Institute of Automation,Chinese Academy of Sciences (IACAS), China.% Revise by Hu Yong, Nov, 2010% E-mail:% based on Matlab 2006a% $Revision: 1.0, Copywrite (c) 2007error(nargchk(1,2,nargin,'struct'));if(nargin < 2), Types = 'all'; endN = length(gMatrix);gMatrix(1:(N+1):end) = 0;%Clear self-edgesCp_Nodal = zeros(N,1); %Preallocateswitch(upper(Types))case 'BINARY'%Binary networkgMatrix = double(gMatrix > 0);%Ensure binary networkfor i = 1:Nneighbor = (gMatrix(i,:) > 0);Num = sum(neighbor);%number of neighbor nodestemp = gMatrix(neighbor, neighbor);if(Num > 1), Cp_Nodal(i) = sum(temp(:))/Num/(Num-1);endcase 'WEIGHTED'% Weighted network -- arithmetic mean for i = 1:Nneighbor = (gMatrix(i,:) > 0); n_weight =gMatrix(i,neighbor); Si = sum(n_weight);Num = sum(neighbor); if(Num > 1),n_weight = ones(Num,1)*n_weight;n_weight = n_weight + n_weight';n_weight = n_weight.*(gMatrix(neighbor,Cp_Nodal(i) = sum(n_weight(:))/(2*Si*(Num-1)); end end %case 'WEIGHTED'% Weighted network -- geometric mean% A = (gMatrix~= 0);% G3 = diag((gMatrix.A(1 ⑶)人3);)% A(A == 0) = inf; %close-triplet no exist,let CpNode=0 (A=inf)% CpNode = G3./(A.*(A-1));case 'DIRECTED', % Directed networkfor i = 1:Ninset = (gMatrix(:,i) > 0);outset = (gMatrix(i,:) > 0)'; %out-nodes setif(any(inset & outset)) allset = and(inset, outset);% Ensure aji*aik > 0,j belongs to inset,and k belongstooutset endneighbor) > 0); %in-nodes settotal = sum(inset)*sum(outset) - sum(allset);tri = sum(sum(gMatrix(inset, outset))); Cp_Nodal(i)= tri./total;endend%Note: Directed & weighted network (from Mika Rubinov) case 'ALL',%All typeA = (gMatrix~= 0); G = gMatrix.A(1/3) + (gMatrix.')4(1/3);D = sum(A + A.',2); g3 = diag(G A 3)/2; D(g3 == 0) = inf; Cp=0c3 = D.*(D-1) - 2*diag(AA2);Cp_Nodal = g3./c3;otherwise,%Eorr Msgerror('Type only four: "Binary","Weighted","Directed",and "All"');endCp_Global = sum(Cp_Nodal)/N;%%第二个文件: CCM_AvgShortestPath.m function [D_Global, D_Nodal] =CCM_AvgShortestPath(gMatrix, s, t)% CCM_AvgShortestPath generates the shortest distance matrix of source nodes % indice s to the target nodes indice t.% Input:% gMatrix symmetry binary connect matrix or weighted connectmatrix source nodes, default is 1:N target nodes, default is 1:N % Usage:% [D_Global, D_Nodal] = CCM_AvgShortestPath(gMatrix) returns the mean% shortest-path length of whole network D_Global,and the mean shortest-path % length of each node in the network % G = gMatrix + gMatrix'; %symmetrized% D = sum(G,2); %total degree % g3 = diag(GA3)/2; %number of triplet% D(g3 == 0) = inf; %3-cycles no exist,let % c3 = D.*(D-1) - 2*diag(gMatrixA2); %number of all possible 3-cycles% Cp_Nodal = g3./c3;%case 'DIRECTED', % Directed network -- clarity format (from Mika Rubinov, UNSW) Cp=0%adjacency matrix %total degree %number of triplet%3-cycles no exist,let% Example:% G = CCM_TestGraph1('nograph');% [D_Global, D_Nodal] = CCM_AvgShortestPath(G);% See also dijk, MEAN, SUM% Written by Yong Liu, Oct,2007% Modified by Hu Yong, Nov 2010% Center for Computational Medicine (CCM),% Based on Matlab 2008a% $Revision: 1.0, Copywrite (c) 2007% ###### Input check #########error(nargchk(1,3,nargin,'struct'));N = length(gMatrix);if(nargin < 2 | isempty(s)), s = (1:N)';else s = s(:); endif(nargin < 3 | isempty(t)), t = (1:N)';else t = t(:); end% Calculate the shortest-path from s to all nodeD = dijk(gMatrix,s);%D(isinf(D)) = 0;D = D(:,t); %To target nodesD_Nodal = (sum(D,2)./sum(D>0,2));% D_Nodal(isnan(D_Nodal)) = [];D_Global = mean(D_Nodal);第三个文件: dijk.m function D = dijk(A,s,t)%DIJK Shortest paths from nodes 's' to nodes 't' using Dijkstra algorithm. % D = dijk(A,s,t)% A = n x n node-node weighted adjacency matrix of arc lengths% (Note: A(i,j) = 0 => Arc (i,j) does not exist;A(i,j) = NaN => Arc (i,j) existswith 0 weight)% s = FROM node indices%= [] (default), paths from all nodes % t = TO node indices%= [] (default), paths to all nodes %D = |s| x |t| matrix of shortest path distances from 's' to 't'%= [D(i,j)], where D(i,j) = distance from node 'i' to node 'j' % % (If A is a triangular matrix, then computationally intensive node% selection step not needed since graph is acyclic (triangularityis a% sufficient, but not a necessary, condition for a graph to beacyclic)% and A can have non-negative elements)% % (If |s| >> |t|, then DIJK is faster if DIJK(A',t,s) used, whereD is now% transposed and P now represents successor indices)% % (Based on Fig. 4.6 in Ahuja, Magnanti, and Orlin, Network Flows, %Prentice-Hall, 1993, p. 109.) % Copyright (c) 1998-2000 by MichaelG. Kay% Matlog Version 1.3 29-Aug-2000%% Modified by JBT, Dec 2000, to delete paths******************************************************error(nargchk(1,3,nargin,'struct'));[n,cA] = size(A);if nargin < 2 | isempty(s), s = (1:n)'; else s = s(:); end if nargin< 3 | isempty(t), t = (1:n)'; else t = t(:); endisAcyclic = 1;elseif ~any(any(triu(A) ~= 0))% A is lower triangular isAcyclic = 2;else % Graph may not be acyclic isAcyclic = 0;end if n ~= cAerror('A must be a square matrix'); elseif ~isAcyclic &any(any(A < 0))error('A must be non-negative'); elseif any(s < 1 | s > n) % Input Error Checking if ~any(any(tril(A) ~= 0)) % A is upper triangularerror(['''s'' must be an integer between 1 and ',num2str(n)]);elseif any(t < 1 | t > n)error(['''t'' must be an integer between 1 and ',num2str(n)]);end************************************** % End (Input Error Checking)**********A = A'; % Use transpose to speed-up FIND for sparse AD = zeros(length(s),length(t));P = zeros(length(s),n);for i = 1:length(s) j = s(i);Di = Inf*ones(n,1); Di(j) = 0;isLab = logical(zeros(length(t),1)); if isAcyclic == 1nLab = j - 1;elseif isAcyclic == 2nLab = n - j;elsenLab = 0; UnLab = 1:n;isUnLab = logical(ones(n,1)); endwhile nLab < n & ~all(isLab)if isAcyclicDj = Di(j);else % Node selection[Dj,jj] = min(Di(isUnLab)); j = UnLab(jj);UnLab(jj) = []; isUnLab(j) = 0; end nLab = nLab + 1;if length(t) < n, isLab = isLab | (j == t); end [jA,kA,Aj]= find(A(:,j));Aj(isnan(Aj)) = 0;if isempty(Aj), Dk = Inf; else Dk = Dj + Aj; endP(i,jA(Dk < Di(jA))) = j; Di(jA) = min(Di(jA),Dk); if isAcyclic == 1 j = j + 1; elseif isAcyclic == 2triangular A j = j - 1;end %disp( num2str( nLab )); endD(i,:) = Di(t)'; end% Increment node index for upper triangular A % Decrement node index for lower。