How to get matrices of edges and nodes from Simulink model

2 次查看(过去 30 天)
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.

回答(1 个)

Yukthi S
Yukthi S 2024-2-16
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:

类别

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