Close figure 1 in matlab only if it exists

Alec Jacobson

March 05, 2013

weblog/

It was annoyingly difficult to find an elegant way to close a certain figure without causing an error if that figure doesn't exist. Using gcf or figure(1) are bad ideas because if the figure doesn't exist then it's created. So calling something like:
close(figure(1));
when figure 1 doesn't exist causes it to open then close. I came up with this instead:
close(intersect(findall(0,'type','figure'),1))