MATLAB: Change “current block”/gcb/gcbh programmatically

current blockgcbgcbhMATLABsimulink

Hey MATLABers,
is there any way to change the current block in Simulink, which will be returned by gcb/gcbh? I would like to start GUIs programmatically, but their code relies on gcb (works perfectly, as long as you start a GUI by double-clickling).
Unfortunately, the following code does not make a block the current block:
>> set_param(hBlock,'Selected','on');
>> isequal(hBlock,gcbh)
ans =
0
Other possibility: programmatically trigger a mouse-click on a Simulink block, but I don't know how…
Thanks very much and best regards
Thomas

Best Answer

Is it not possible to change the code to use block path (string such as 'myModel/Gain') instead of gcb or gcbh? This would be the most straightforward thing to try. If you cannot do this for various reasons:
How do you get the value of hBlock? If you are hard coding it as a variable (by specifying a number) there could be two issues with this:
  1. As this documentation says, You can use the block handle in subsequent calls to get_param or set_param. If you examine the handle, you can see that it contains a double. Do not try to use the number of a handle alone (e.g., 5.007) because you usually need to specify many more digits than MATLAB displays. Instead, assign the handle to a variable and use that variable name to specify a block. Use getSimulinkBlockHandle to get the handle to a block.
  2. Using hard coded values might result in breaking of logic since Simulink can change the handle to the block every time the model is loaded/opened. For e.g it could be 16.0001 now. If I close and open the model again, it maybe different.
  3. I am guessing the equality test might fail because you are trying to compare two floating point numbers.
For e.g. if I do this, it seems to work:
%Open demo model
vdp
%Set Mu block as selected
set_param('vdp/Mu','Selected','on')
%Get Handle to the block
hBlock = getSimulinkBlockHandle(gcb)
%Compare handle value to gcbh
isequal(hBlock,gcbh)
If you run this code mutliple times (each time clearing workspace and closing the open vdp model), you can see the value of hBlock keeps changing.