How to change node names and divide and print the individual graph?

2 次查看(过去 30 天)
I have this graph
Gp = graph({'n1' 'n1' 'n2' 'n2' 'n3' 'n4'},{'n2' 'n4' 'n3' 'n4' 'n5' 'n5'});
how to change node name without altering the existing one? say i would like to change n1 as [s1,s_1]
Can we able to add Weights for Node? And is it possible to represent weight of node in the graph by plotting ?
As well as how to print a graph containing desired nodes from the Gp GRAPH? just to print say n1,n2,n3

回答(1 个)

Rahul
Rahul 2025-6-23
Hi Aswin,
I understand that you’re trying to work with MATLAB’s 'graph' objects, to rename nodes, assign weights to individual nodes, visualize those weights, and extract a subgraph containing only selected nodes. Moreover, this is to be achieved without disrupting the existing graph structure.
Starting with node renaming, you can update the 'Name' property of nodes directly through the Nodes table. For example, to rename 'n1' to '[s1,s_1]', you can use the following approach:
idx = strcmp(Gp.Nodes.Name, 'n1');
Gp.Nodes.Name{idx} = '[s1,s_1]';
This preserves the structure of the graph while updating only the node label. Just make sure that the new names remain unique and are treated as valid strings.
Regarding node weights, MATLAB doesn’t natively support weights on nodes like it does for edges, but you can add a custom variable to the Nodes table to represent node-specific attributes such as weight, cost, or priority. Here is how you achieve the same:
Gp.Nodes.Weight = [10; 20; 30; 40; 50]; % Example weights
These weights won’t affect the connectivity of the graph but can be useful for visualization or downstream analysis. In case you want to represent these weights visually, you can scale marker sizes in the plot accordingly as shown below:
p = plot(Gp, 'NodeLabel', Gp.Nodes.Name, ...
'MarkerSize', rescale(Gp.Nodes.Weight, 5, 15)); % Adjust marker size based on weight
Finally, to extract and visualize a subgraph containing only a subset of nodes, say 'n1', 'n2', and 'n3', you can use the subgraph function as shown below:
subNodes = {'n1', 'n2', 'n3'};
GpSub = subgraph(Gp, subNodes);
plot(GpSub, 'NodeLabel', GpSub.Nodes.Name);
This should generate a new graph with just the specified nodes and any edges among them that existed in the original graph.
For more information regarding the usage of various functions utilized in the given code snippet, you can refer to the following documentation links:
Hope this helps!

类别

Help CenterFile Exchange 中查找有关 Graph and Network Algorithms 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by