How to set the nearest position of the block from the Simulink from Matlab script?

R
rajansingh · Oct 20, 2021 · 2.3K views
Question
Hi!   I am working on automated Simulink models transformations (creating models from Matlab Scipt) and I need to:   (a) add a block to simulink from the Matlab script - DONE, (b) connect it to desired port - DONE, (c) put this block close to the connected port - NEED HELP.   I have found that the set_param function is able to change the position, but I have to know the exact coordinations: set_param(['sampleModel' '/' 'From'],'Position',[0 50 0 50])   I need to set the nearest possible location of the block to its connected port. It is something like:   set_param(['sampleModel' '/' 'From'],'Position','Nearest'). There is any option in 'Position' that there is no need to put exact coordinations but only "Nearest"?   How can I achieve that?
Expert Answer
Profile picture of John Michell
John Michell PhD Expert
Answered Aug 13, 2026
For doing this you need to extract position of ports (both inport and outport) of each subsystem then.
 
you can do like below
Modelname = 'dummy';
new_system(Modelname);
open_system(Modelname);
add_block('built-in/Subsystem',[Modelname '/Subsystem'],'Position',[200 200 300 500]);
add_block('simulink/Sinks/Out1',[Modelname '/Subsystem/out1']);
add_block('simulink/Sources/In1',[Modelname '/Subsystem/in1']);

%% from here your point C begins
%get porthandles
PH = get_param([Modelname '/Subsystem'],'PortHandles');
%get position of inport and outport ports of subsystem
ipportpos = get(PH.Inport,'Position');
opportpos = get(PH.Outport,'Position');
%add from and goto blocks
gotoblockhandle = add_block('simulink/Signal Routing/From',[Modelname '/goto']);
fromblockhandle = add_block('simulink/Signal Routing/Goto',[Modelname '/from']);
%set position near to subsystem you can change 70 100  and 7 on how far you
%want to keep and size of block
set_param(fromblockhandle,'Position',[opportpos(1)+70 opportpos(2)-7 opportpos(1)+100 opportpos(2)+7 ]);
set_param(gotoblockhandle,'Position',[ipportpos(1)-100 ipportpos(2)-7 ipportpos(1)-70 ipportpos(2)+7 ]);

 

Have a different question? Ask here

Get a Free Consultation or a Sample Assignment Review!