MATLAB exercise program (prim minimal spanning tree)

Source: Internet
Author: User

AlgorithmSteps:

1. Add any vertex to the tree.

2. Search for all the elements adjacent to the tree, and take the elements with the smallest Edge Weight and not included in the tree into the tree.

3. Continue Step 2 until all elements are in the tree.

The effect is similar to that of the Kruskal algorithm.

MATLABCode:

Main. m

 Clear all; close all; clc; G = [ 0   4   0   0   0   0   0   8   0  ; 4   0   8   0   0   0   0   11   0  ;  0   8   0   7   0   4   0   0   2 ;  0   0   7   0   9   14   0   0   0  ;  0   0   0   9   0   10   0   0  0  ;  0   0   4   14   10   0   2   0   0  ;  0   0   0   0   0   2   0  1   6  ;  8   11   0   0   0   0   1   0   7  ;  0   0   2   0   0   0  6   7   0  ];  [M n] = Size (g); q = [ 1  ]; % The Marked element K = 1  ; % Number of marked elements = []; % The Last generated Minimum Spanning Tree  While Length (q )~ = M e = [];  For I =1  : K  For J = 1  : N  If G (Q (I), j )~ = 0 && ~ Biaoji (J, q) % Element E in the number = [E; G (Q (I), j) q (I) J];  End          End      End  [Junk Index] = Min (E (:, 1 ); % Calculate the index A of the edge with the smallest weight adjacent to all elements currently marked = [A; E (index, :)]; % the triples of the Minimum Spanning Tree represent Q = [Q e (index, 3  )]; K = K + 1  ;  End 

Biaoji. m

FunctionRe =Biaoji (J, Biao) % determines if J points have been marked L=Length (Biao );ForI =1: LIfJ =Biao (I) Re=1; Return;EndEndRe=0; Return;End

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.