Guest User

Matlab: Weighted graph

a guest
Jul 19th, 2014
398
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. %% code for SO question: http://stackoverflow.com/questions/24744959
  2. clear
  3. %% generate testing data
  4. [X,Y] = ndgrid(1:20); testdata = [X(:) Y(:)]; % all possible edges
  5. testdata(testdata(:,1)==testdata(:,2),:)=[]; % delete self loops
  6. testdata=testdata(randperm(size(testdata,1),30),:); % take random sample of edges
  7. testdata(:,3)=rand(size(testdata,1),1)*10; % assign random weights in range 0-10
  8.  
  9. %% get data into useable format
  10. edges=testdata(:,1:2); %
  11. [Verticies,~,indEdges]=unique(edges);
  12. indEdges=reshape(indEdges,[],2);
  13.  
  14. weights=testdata(:,3);
  15. normalisedWeights=weights/max(weights);
  16. numeEdge=numel(weights);
  17.  
  18. numVertex=numel(Verticies);
  19.  
  20. %% create x,y coordinates for each vertex
  21. theta=linspace(0,2*pi,numVertex+1);
  22. theta=theta(1:end-1);
  23. [x,y]=pol2cart(theta,1);
  24.  
  25. %% create axis colour order
  26. colormap('autumn')
  27.  
  28. Cmap(:,2)=normalisedWeights;
  29. Cmap(:,1)=1;
  30. Cmap(:,3)=0;
  31.  
  32. %% plot edges
  33. figure
  34. colormap('autumn')
  35. hold on
  36. set(gca,'colororder',Cmap)  % set axis colororder to Cmap
  37. hline=plot(x(indEdges).',y(indEdges).'); %plot edges
  38. axis square off
  39.  
  40. set(gca,'Clim',[0 max(weights)])
  41. colorbar    %set colour limit to match weight & add colorbar
  42.  
  43. scalefactor=5; %// scale factor (width of highest weight line)
  44. set(hline, {'LineWidth'}, num2cell(normalisedWeights*scalefactor));
  45.  
  46. %% plot Verticies
  47. plot(x,y,'ks')
  48.  
  49. xlim([-1.1,1.1]) % expand axis to fix labels
  50. ylim([-1.1,1.1])
  51. text(x(:)*1.1, y(:)*1.1, num2str(Verticies), 'FontSize',8,'HorizontalAlignment','center');
  52.                             % add Vertex labels
Add Comment
Please, Sign In to add comment