MATLAB: How to display figure on a specific monitor when there are multiple screens

MATLAB

I use a computer with multiple screens. I would like to have my new figures spawn on a screen that I specify instead of the main display screen. It would be wonderful if MATLAB could detect the number of displays connected, and let me pass the display number to "figure". If the display vanishes during the execution, fall back to alternate displays.
It would be nice to have a method where I did not have to compute the pixels. If the code executes after a monitor gets disconnected the figure is out of the viewable screen.

Best Answer

There is no way to use "figure" to explicitly set which monitor the figure displays on, but there is a workaround that is fairly straightforward.
Using the "MonitorPositions" root object you can get the position of each display in MATLAB "Position" arguments
And then you can set the "Position" of the figure to that. To do this for the secondary monitor execute the following MATLAB commands:
>> p = get(0, "MonitorPositions")
>> f.Position = p(2, :) % second display
>> f.WindowState = "maximized"
Using "WindowState" set to "maximized" prevents overlap with docks and status bars on the screen.
To do this for the primary monitor, this code applies:
>> f.Position = p(1, :) % first display
>> f.WindowState = "maximized"
If you want every figure to open in the size the current figure is, you can set the "DefaultFigurePosition" in the graphics root settings, see the "Default Property Values" documentation page for more information:
>> set(0, "DefaultFigurePosition", f.Position
To undo this and return figures to their standard default settings, execute\n
>> set(0, "DefaultFigurePosition", 'remove')