MATLAB: Is it possible to delete a Simulink block from the block’s callback function

blockcallbackcopyfcndeletesimulinksingleton

I would like to create singleton Simulink blocks. In other words, if a user tries to create a copy of the Simulink block, the copy should automatically get deleted. I have tried to implement this in the block's CopyFcn callback. But the block does not get deleted, and I get the following warning:
Warning: Error evaluating 'CopyFcn' callback of Sin block 'mymodel/Sine Wave1'. Error using ==> delete_block
Cannot delete 'mymodel/Sine Wave1' while in a callback.

Best Answer

Simulink does not allow a block's callback function to delete the block. This is because a callback is often just one operation in a larger potentially nested sequence of operations being performed on a block. Deleting the block before these operations are completed can cause MATLAB or Simulink to crash. It would be analogous to referencing a pointer in C/C++ that has already been deleted. To work around this issue, you can perform preprocessing when you start your model by deleting any duplicate blocks that exist in your model from the StartFcn model callback.