MATLAB: Assigning values to nodes of a graph

graphMATLABnodeplot

I'm assigning values to nodes of a graph
tail = 1:9;
head = 2:10;
G = graph(tail,head);
data = 1:10;
G.Nodes.Value = data';
p = plot(G)
p.Marker = 's';
p.MarkerSize = 7;
p.NodeCData = G.Nodes.Value;
colorbar
The above works fine.
Let's say there are no values for nodes 1 and 10 (head and tail). I'm not sure how to assign values in such a case. I could simply do rmnode(G,[1,10]), but this renumbers all the nodes. I actually plot the graph,G, and visualize the values at each node, so I don't want the nodes to be renumbered.
Any suggestions on how to proceed will be highly appreciated.

Best Answer

It sounds like you want to associate a unique ID to each node, one that doesn't change if you alter the graph. You can't use the node number for that as indeed this changes when you add/remove edges or get a subset of the graph.
The best thing is to give a name to the nodes. The node names will then be used automatically for plot as node labels and the names won't change when the graph is edited. Unfortunately, matlab will not let you use numbers as node names, it has to be a string or char vector.
tail = 1:9;
head = 2:10;
G = graph(tail,head);
G.Nodes.Name = string(1:height(G.Nodes))'; %for example
%or G.Nodes.Name = num2cell(char('A' + (0:height(G.Nodes)-1)))'; %for letters
figure; subplot(1, 2, 1);
p1 = plot(G);
G = rmnode(G, [1, 10]);
subplot(1, 2, 2);
p2 = plot(G); %notice that the labels have been preserved
Related Question