[英]MATLAB: Fast creation of random symmetric Matrix with fixed degree (sum of rows)
[英]Cost-effective creation of a symmetric matrix in MATLAB
我對MATLAB很新,並且有一段代碼可以創建一個距離矩陣。 更確切地說,它在位於無向圖上的點之間創建距離矩陣D,使得Dij是該圖上的點之間的最短路徑。 這個矩陣顯然是對稱的(因為圖是無向的),以下是我用來創建它的代碼片段:
D = zeros(size(data,1));
for i = 1:size(data, 1)
for j = 1:size(data, 1)
[D(i, j), ~, ~] = graphshortestpath(G, i, j, 'Directed', false);
end
end
這顯然非常浪費,因為我沒有利用矩陣的對稱性。 有什么方法我只能計算矩陣的上三角形部分然后以某種方式將下三角形部分“追加”到它,這樣我就可以將計算從n ^ 2減少到n ^ 2/2?
任何幫助,贊賞,
賈森
當然。 只需考慮迭代的順序,找出首先達到的三角形。
D = zeros(size(data,1));
for i = 1:size(data, 1)
for j = 1:size(data, 1)
if j > i
[D(i, j), ~, ~] = graphshortestpath(G, i, j, 'Directed', false);
else
D(i, j) = D(j, i);
end
end
end
如果對角線元素不是相同的零,則可以使用if j >= i
。
對於無向和未加權的圖形,計算距離矩陣的另一種方法
如果您試圖減少運行時間,可能會有所幫助。 在Matlab的情況下,大多數時候,我發現按入口掃描輸入速度較慢。 我只是猜測你問這個問題的目的,對不起,如果我不在話題。
給定鄰接Matix(G),我會按以下方式計算距離矩陣,
假設:1。G是無向和未加權的(矩陣填充'0'和'1')2。N是圖的順序,G的大小為N x N
function [D,connect]=genDistance(G,N)
D = G;
B = G;
connect = 0;
i=1;
while((~connect)&&(i<N-1)) % the maximum distance from one vert to another
i = i + 1; % is N-1
B = B * G; % G to the power of i
D = D + i * (D==0&B>0); % D==0 & B>0 the entries to be updated
connect = ( min(min(D)) )>0; %check if D has zero entry
end
D ( eye(N) ) = 0 ; %clear diagonal entries
您可以為矩陣G
的下半部分生成索引
N = length(G);
[irow, icol] = find(tril(ones(N),-1));
然后你可以遍歷這些索引:
D = zeros(size(G));
for i = 1:numel(irow)
[D(irow(i), icol(i)] = graphshortestpath(G, irow(i), icol(i), 'Directed', false);
end
D = D + D';
另一個選擇是使用帶有索引的ARRAYFUN和SQUAREFORM將結果向量轉換為方形矩陣:
D = arrayfun(@(x,y) graphshortestpath(G,x,y, 'Directed', false), irow, icol);
D = squareform(D);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.