matlabportsimulinksubsystem

What is the correct way to connect inports to a subsystem in Matlab/Simulink? I'm getting Invalid Simulink object name


I'm working with a model in Simulink, that contains a lots of inports and outports, and a subsystem. I'm trying to connect them programmatically because it is a really huge model.

I've tried getting the handles of the ports, using the name of the ports, and I'm still getting errors like "Invalid Simulink object name" or "Invalid Simulink port handle"

The following code will create a minimum subsystem, I would like to recall that in the real system I'm working there could be 50+ ports, and them does not necessarily connect "one by one", I mean, sometimes the first inport will be connected to the third inport from the subsystem, for example.

% Creating little subsystem and inports
open_system(new_system('my_system'));
add_block('simulink/Commonly Used Blocks/In1', 'my_system/port_name_1');
add_block('simulink/Commonly Used Blocks/In1', 'my_system/port_name_2');
add_block('built-in/Subsystem', 'my_system/test_subsystem');
add_block('simulink/Commonly Used Blocks/In1', 'my_system/test_subsystem/test_name_1');
add_block('simulink/Commonly Used Blocks/In1', 'my_system/test_subsystem/test_name_2');

Model with inports and subsystem

Here is where I get some of the error messages:

add_line('my_system', 'my_system/port_name_1', 'my_system/test_subsystem/test_name_1', 'autorouting', 'smart');

% Error: Invalid Simulink object name: my_system/port_name_1
porthandle = get_param('my_system/port_name_1', 'Handle');
subsystem_port_handle = get_param('my_system/test_subsystem/test_name_1', 'Handle');
add_line('my_system', porthandle, subsystem_port_handle, 'autorouting', 'smart');

% Error: Invalid Simulink port handle

Solution

  • As per the doc for add_block, the correct syntax in each case is

    add_line('my_system', 'port_name_1/1', 'test_subsystem/1', 'autorouting', 'smart');
    

    and

    porthandle = get_param('my_system/port_name_1', 'PortHandles');
    subsystem_port_handle = get_param('my_system/test_subsystem', 'PortHandles');
    add_line('my_system', porthandle.Outport(1), subsystem_port_handle.Inport(1), 'autorouting', 'smart');