How to connect Inport Inport or Outport Outport programmatically
11 次查看(过去 30 天)
显示 更早的评论
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:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1654401/image.png)
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
0 个评论
回答(1 个)
Fangjun Jiang
2024-3-28
编辑:Fangjun Jiang
2024-3-28
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Subsystems 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!