问题
Could you please tell me why this MATLAB code is wrong? I don't understand why. Thank you so much in advance.
function [mst, cost] = prim(A)
[n,n] = size(A);
A, n, pause,
if norm(A-A','fro') ~= 0 ,
disp(' Error: Adjacency matrix must be symmetric ')
return,
end;
intree = [1]; number_in_tree = 1;
number_of_edges = 0;
notintree = [2:n]'; number_notin_tree= n-1;
in = intree(1:number_in_tree),
out = notintree(1:number_notin_tree),
pause,
while number_in_tree < n,
mincost = Inf;
for i=1:number_in_tree,
for j=1:number_notin_tree,
ii = intree(i); jj =
notintree(j);
if A(ii,jj) < mincost,
mincost = A(ii,jj); jsave = j;
iisave = ii; jjsave = jj;
end;
end;
end;
number_of_edges = number_of_edges +1;
mst(number_of_edges,1) = iisave;
mst(number_of_edges,2) = jjsave;
costs(number_of_edges,1) = mincost;
number_in_tree = number_in_tree + 1;
intree = [intree; jjsave];
for j=jsave+1:number_notin_tree,
notintree(j-1) = notintree(j);
end;
number_notin_tree = number_notin_tree - 1;
in = intree(1:number_in_tree),
out = notintree(1:number_notin_tree),
pause,
end;
disp(' Edges in minimum spanning tree and their costs: ')
[mst costs]
cost = sum(costs)
When I click the run button says:
Not enough input arguments.
Error in prim (line 10)
[n,n] = size(A);
% The matrix is n by n, where n = # nodes.
However when I call the function in the Command window with
s=[1 1 2 2 2 3 3 4 4 4 5 5 6 7];
t=[2 3 4 5 3 5 6 5 7 8 6 8 7 8];
w=[3 5 4 7 4 9 8 3 11 8 3 9 8 7];
G = graph(s,t,w);
A = adjacency(G);
prim(A)
The code works 'correctly'
As a final answer returns
mst =
cost=
All zero sparse: 1-by-1
It should have returned
mst=
1 2
2 3
2 4
4 5
5 6
6 7
7 8
costs=32
Why did not returned that?
Whilst running the program went from 1 to 4 though it should have gone to 2. Then from 4 to 5, that was correct but I don't know why skipped 2 and 3 and went directly to 4,5,6,7,8.
Help me please.
If there is an alternative code that you know please provide it, perhaps an easier one.
回答1:
The main problem with your function is that when you check to see if the current edge has lower cost than mincost, you don't verify that there's actually an edge there. If there's no edge, then the cost will be 0, which is naturally lower than any positive cost value. You need to change the line:
if A(ii,jj) < mincost,
to
if (A(ii,jj) > 0) && (A(ii,jj) < mincost), % A(ii,jj) is edge and lower cost than mincost
Adjacency matrix used as input:
A =
0 3 5 0 0 0 0 0
3 0 4 4 7 0 0 0
5 4 0 0 9 8 0 0
0 4 0 0 3 0 11 8
0 7 9 3 0 3 0 9
0 0 8 0 3 0 8 0
0 0 0 11 0 8 0 7
0 0 0 8 9 0 7 0
The output after this change is:
mst =
1 2
2 3
2 4
4 5
5 6
4 8
8 7
cost = 32
来源:https://stackoverflow.com/questions/53568255/find-a-minimum-spanning-tree