How to connect Inport Inport or Outport Outport programmatically

12 views (last 30 days)
Is their a way to connect input to an input or output to an ouput in a simulink model programatically. In fact, I am creating a matlab script that connects all port of my top level. However, I was able only to connect subsystems ports as add _line is not able to connect Inport to inport or outport to outport like this:
function Control_Model(modelName)
load_system(modelName)
% find the top-level subsystems
subsystems = find_system(modelName, 'SearchDepth', 1, 'BlockType', 'SubSystem');
% Verification
disp(subsystems);
% get outports for each subsystem(i)
for i = 1:length(subsystems)
outportNames = get(find_system(subsystems{i}, 'FindAll', 'on', 'SearchDepth', 1, 'BlockType', 'Outport'), 'Name');
subsystems_i_Ports =get_param(subsystems{i},'PortHandles');
if ischar(outportNames), outportNames = {outportNames}; end
% get inports from each subsystem(j) and look for matched names
for j = 1:length(subsystems)
if i ~= j % Avoid self-connection
inportNames = get(find_system(subsystems{j}, 'FindAll', 'on', 'SearchDepth', 1, 'BlockType', 'Inport'), 'Name');
subsystems_j_Ports =get_param(subsystems{j},'PortHandles');
if ischar(inportNames), inportNames = {inportNames}; end
% connect matching ports
for k = 1:length(outportNames)
for l = 1:length(inportNames)
if strcmp(outportNames{k}, inportNames{l})
% Verification
disp(['Connecting ', subsystems{i}, ' ', outportNames{k}, ' to ', subsystems{j}, ' ', inportNames{l}]);
% connection
add_line(modelName,subsystems_i_Ports.Outport(k),...
subsystems_j_Ports.Inport(l));
end
end
end
end
end
end

Answers (1)

Fangjun Jiang
Fangjun Jiang on 28 Mar 2024 at 14:22
Edited: Fangjun Jiang on 28 Mar 2024 at 14:32
Yes. You can!
I have done that using the add_line('connect_model','Constant/1','Gain/1') syntax by matching name.
You are connecting blocks using port handles with the add_line('vdp',h.Outport(1),h1.Inport(2)) syntax.
I think you can include Inport and Outport blocks in the find_system() code running on the top-level subsystem. Treat them as if they are subsystem blocks. They do have the same 'PortHandles' property. Maybe need to do things differently to get the port name (which is the block name). Then, the double-loop code should be able to connect them. I think this is better because it does not require too many special processing.
The other approach is to do a little more special processing, go through a loop, try connecting all Inport blocks to the Inports of all subsystem blocks by matching name. Another loop to connect all subsystem outports to all Outport blocks.
Adding a check for duplicated outport names could be an enhancement.

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!