Create and activate figures by name

Finds and activates, or creates, figure with user-specified name.
Updated 8 Jan 2015

View License

Editor's Note: This file was selected as MATLAB Central Pick of the Week

Finds and activates, or creates, figure with user-specified name.

If no name is provided, creates figure named "untitledn" (where n is incremented to result in a unique name).

togglefig('My Figure');
If figure named 'My Figure' exists, it will be activated (brought to the front and shown). Otherwise, it will be created.

h = togglefig('My Figure');
Also returns the handle to the specified or created figure.

Creates and activates new figure named untitled1, untitled2, ...
Note: You can subsequently activate these figures with, for instance, togglefig('untitled1').

NOTE: This example requires the Image Processing Toolbox
im = imread('cameraman.tif');
for ii = 1:10
thresh = ii/20;
title(sprintf('Threshold = %0.2f',thresh));
I've found this to be exceptionally useful in algorith-development
mode, particularly when iterating on cells in the cell-mode editor. (I
use this function in almost every mfile I write these days.)

Cite As

Brett Shoelson (2024). Create and activate figures by name (, MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2007b
Compatible with any release
Platform Compatibility
Windows macOS Linux
Find more on Graphics Objects in Help Center and MATLAB Answers

Inspired: Cell Cycle Analysis, Cell Cycle Analysis

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
Version Published Release Notes

R2014b ready.

Fixes a bug when togglefig is called with no input arguments. Thanks to Danilo for pointing it out!

I added a new (optional) input argument that triggers a CLF (clear-figure) command.

Minor modification to suppress handle generation if no output is requested.