早知道有向圖和無向圖差別沒有想象中的大我就寫到一起了。
函數中使用的arrow畫箭頭函數是在這個網站下的。
%函數名netplot %使用方法輸入請help netplot %無返回值 %函數只能處理有向圖 %作者:tiandsp %最后修改:2012.12.26 function netplot(A,flag) %調用方法輸入netplot(A,flag),無返回值 %A為鄰接矩陣或關聯矩陣 %flag=1時處理鄰接矩陣 %flag=2時處理關聯矩陣 %函數只能處理有向圖 if flag==1 %鄰接矩陣表示有向圖 D_netplot(A); return; end if flag==2 %關聯矩陣表示有向圖 [m n]=size(A); %關聯矩陣變鄰接矩陣 W=zeros(m,m); for i=1:n a=find(A(:,i)~=0); if A(a(1),i)==1 W(a(1),a(2))=1; else W(a(2),a(1))=1; end end D_netplot(W); return; end function D_netplot(A) [n n]=size(A); w=floor(sqrt(n)); h=floor(n/w); x=[]; y=[]; for i=1:h %使產生的隨機點有其范圍,使顯示分布的更廣 for j=1:w x=[x 10*rand(1)+(j-1)*10]; y=[y 10*rand(1)+(i-1)*10]; end end ed=n-h*w; for i=1:ed x=[x 10*rand(1)+(i-1)*10]; y=[y 10*rand(1)+h*10]; end plot(x,y,'r*'); title('網絡拓撲圖'); for i=1:n for j=1:n if A(i,j)~=0 c=num2str(A(i,j)); %將A中的權值轉化為字符型 text((x(i)+x(j))/2,(y(i)+y(j))/2,c,'Fontsize',10); %顯示邊的權值 arrow([x(i) y(i)],[x(j) y(j)]); %帶箭頭的連線 end text(x(i),y(i),num2str(i),'Fontsize',14,'color','r'); %顯示點的序號 hold on; end end end end
運行結果: