Clear Filters
Clear Filters

How to get matrices of edges and nodes from Simulink model

2 views (last 30 days)
I have a simulink model and I want to create a digraph of the block connections. I used the 'Portconnectivity' command to find each blocks source and destination block. I don't know how to create a digraph using the information from the 'Portconnectivity' command because I don't want to manually input all the nodes and edges. How do I generate a matrix of the nodes and edges in a Simulink model without manually inputting them so I can make a digraph of the block connections.

Answers (1)

Yukthi S
Yukthi S on 16 Feb 2024
Hi Madison Ohara
I got that you wanted to create digraph of the block connections without manually giving input nodes and edges.
I assume that you are using the latest Release of MATLAB since you did not mention any information about that.
The following MATLAB code will help you generate the digraph.
% Load the Simulink model (replace 'modelname' with the name of your model)
modelname = 'name_of_your_model';
load_system(modelname);
% Get a list of all blocks in the model
blocks = find_system(modelname, 'Type', 'Block');
% Initialize source and target node lists
sourceNodes = {};
targetNodes = {};
% Loop through each block and get its port connectivity
for i = 1:length(blocks)
% Get port connectivity information for the current block
ports = get_param(blocks{i}, 'PortConnectivity');
% Loop through each destination port
for j = 1:length(ports)
dstBlock = ports(j).DstBlock;
% Check if the destination block handle is valid (not -1)
if dstBlock ~= -1
% Get the name of the destination block
dstBlockName = getfullname(dstBlock);
% Add the source and target nodes to the lists
sourceNodes{end+1} = getfullname(blocks{i}); % Source block name
targetNodes{end+1} = dstBlockName; % Destination block name
end
end
end
% Create the directed graph from the node lists
G = digraph(sourceNodes, targetNodes);
% Plot the graph
figure;
plot(G);
You can also refer to the MATLAB documentation links of all the functions used in the above code:

Categories

Find more on Graph and Network Algorithms in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!