Home > matlab, Physics > Howto : Prevent figures from stealing focus in MATLAB

Howto : Prevent figures from stealing focus in MATLAB

Regular users of MATLAB will have noticed that figure windows have a nasty tendency to steal the focus from other windows. If you are making regular updates to a figure while in a loop, this makes it impossible to, say, use a browser while the script is running. Read on for a solution to this problem(!)

To get around this, download this script: sfigure.m and put it in your MATLAB path (or in your current working directory). Then replace all calls to figure() with calls to sfigure(). Now, your figures will no longer take focus.

The code can be seen below.

function h = sfigure(h)
% SFIGURE  Create figure window (minus annoying focus-theft).
%
% Usage is identical to figure.
%
% Daniel Eaton, 2005
%% See also "help figure"
if nargin>=1
if ishandle(h)
    set(0, 'CurrentFigure', h);
else
    h = figure(h);
end
else
    h = figure;
end

Credits:
Daniel Eaton. http://www.cs.ubc.ca/~deaton/

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
Categories: matlab, Physics Tags:
  1. matt
    February 13th, 2009 at 02:10 | #1

    You copied the code wrong and left out the first line. It should be:

    if nargin>=1
    if ishandle(h)
    set(0, ‘CurrentFigure’, h);
    else
    h = figure(h);
    end
    else
    h = figure;
    end

  2. Bass
    May 28th, 2009 at 00:07 | #2

    This doesn’t work for me

  3. admin
    May 31st, 2009 at 22:39 | #3

    The code should be fixed now!

  4. Rob
    January 7th, 2010 at 18:02 | #4

    Doesn’t work for me either. I’m on Linux (KDE 4/Ubuntu)

  5. Nik
    April 15th, 2010 at 14:37 | #5

    Many, many, many thanks for this! It’s great to be able to do something else while MATLAB plots away. Works like a charm.

  6. vinc
    October 8th, 2010 at 14:14 | #6

    Hi, this code does not work for me, Matlab says:
    ??? Error using ==> sfigure
    Too many input arguments.

    So I modify the code with the following which works well:

    function h = sfigure(varargin)
    if nargin>=1
    if ishandle(varargin{1})
    set(0, ‘CurrentFigure’, varargin{1});
    else
    h = figure(varargin{:});
    end
    else
    h = figure;
    end

    Thanks anyway!

  7. Fil
    August 19th, 2011 at 11:41 | #7

    Thanks, this trick works like a charm.
    I went one step further. In order to get full functionality of figure with a variable input number of arguments (properties) and overloading the builtin figure you can use:

    function varargout = figure(varargin)
    if nargin>=1
    if ishandle(varargin{1})
    set(0, ‘CurrentFigure’, varargin{1});
    else
    h = builtin(‘figure’,varargin{:});
    end
    else
    h = builtin(‘figure’);
    end
    if nargout
    varargout(1) = {h};
    end

  1. No trackbacks yet.