67

I have nine open figures in matlab (generated by another function) and I want to print them all to file. Does anyone know how to grab the handles of all open figures in MATLAB?

I know about gcf but it doesn't seem to do what I want.

Amro
  • 123,847
  • 25
  • 243
  • 454
Liz
  • 673
  • 1
  • 5
  • 4

4 Answers4

85

There are a few ways to do this. One way to do this is to get all the children of the root object (represented in prior versions by the handle 0):

figHandles = get(groot, 'Children');  % Since version R2014b
figHandles = get(0, 'Children');      % Earlier versions

Or you could use the function findobj:

figHandles = findobj('Type', 'figure');

If any of the figures have hidden handles, you can instead use the function findall:

figHandles = findall(groot, 'Type', 'figure');  % Since version R2014b
figHandles = findall(0, 'Type', 'figure');      % Earlier versions
gnovice
  • 125,304
  • 15
  • 256
  • 359
  • The first argument to `get()` and `findall()` is a handle. What is meant when 0 is provided? – Minh Tran May 15 '17 at 23:59
  • 2
    @MinhTran: That is a holdover from prior versions, when the root object was represented by the handle `0`. It still works in newer versions, but it's better to use `groot`. I've updated my answer accordingly. – gnovice May 16 '17 at 02:40
18

One of the best things to do is to NOT need to look for the handles. When you create each figure, capture its handle.

h(1) = figure;
h(2) = figure;
...

As one of the developers here told me:

They are called handles, because you are supposed to hold on to them

dynamic
  • 46,985
  • 55
  • 154
  • 231
MatlabDoug
  • 5,704
  • 1
  • 24
  • 36
  • 7
    That is a good point, though it depends on your situation and workflow. If you have a wide variety of plotting commands that bring up different specialized plots and you want something that just "deals with whatever happens to be up already" it can be useful to be able to query for handles. –  Mar 15 '12 at 15:42
  • 4
    Also, there a few functions out there that will plot many figures for you (`anova1` will plot three) and they may not return you those handles – Tex Sep 15 '13 at 14:11
12

I think findall should work

handles=findall(0,'type','figure')

zellus
  • 9,617
  • 5
  • 39
  • 56
Chris
  • 1,532
  • 10
  • 19
7

You've get fine answers for the handles mass. But another tip for the original question- print all the figures to file: you can use publish option, without dealing with figrues or handles.

Adiel
  • 3,071
  • 15
  • 21
  • 1
    +1. Considering how powerful this relatively unknown command is, I'm surprised there aren't more upvotes. – Peter D Mar 31 '14 at 22:26
  • 1
    Just logged in after months of absence, just to upvote that answer that Google just pointed me at. – user2987828 Feb 22 '17 at 12:31